【问题标题】:To get the field name in an entity using column name使用列名获取实体中的字段名
【发布时间】:2019-11-27 02:10:49
【问题描述】:

有没有办法使用列名获取实体中的字段名。

@Table(name = "ESTABLISHMENT")
public class Establishment implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "EST_CODE")
    private Long code;


    @Column(name = "W_CODE")
    private Long wCode;

}

//服务

我有 W_CODE 名称,有什么方法可以获取实体中的字段名称。这里是它的 wCode。 我想用它来创建自定义 JPQL 查询。

【问题讨论】:

    标签: spring spring-boot spring-data-jpa jpql


    【解决方案1】:

    可以解析列注解:

    for (Field field : entity.getClass().getDeclaredFields()) {
       Column column = field.getAnnotation(Column.class);
       if (column != null) {
          columnNames.add(column.name());
       }
    }
    

    【讨论】:

    • 如果你更多地挖掘 Field 对象,你会得到很多其他的东西,比如字段名称、存在的注释及其值等等。
    【解决方案2】:

    您可以使用实体或模型获取列名称列表。我们需要的是@Column,它应该在您的实体中使用。您将获得在@Column 中指定的所有详细信息。所有参数都是可选的,虽然最好全部定义。

    @Column(name, columnDefinition, 可插入, 长度, 可空, 精度、比例、表格、唯一、可更新)

    我们可以通过User.class.getDeclaredFields()获取Entity中声明的所有字段(一般是ModelName.class.getDeclaredFields())。获取所有字段后,我们可以使用field.getAnnotation(Column.class) 获取特定的列,我们还可以获取@Column 中指定的所有详细信息,如下所示

    Columns: @javax.persistence.Column(nullable=false, precision=2, unique=true, name=id, length=2, scale=1, updatable=false, columnDefinition=, table=, insertable=true)
    Columns: @javax.persistence.Column(nullable=true, precision=0, unique=false, name=client_id, length=255, scale=0, updatable=true, columnDefinition=, table=, insertable=true)
    Columns: @javax.persistence.Column(nullable=true, precision=0, unique=false, name=firstname, length=255, scale=0, updatable=true, columnDefinition=, table=, insertable=true)
    Columns: @javax.persistence.Column(nullable=true, precision=0, unique=false, name=lastname, length=255, scale=0, updatable=true, columnDefinition=, table=, insertable=true)
    

    根据需求创建端点或方法

    @GetMapping(value= "/columns/name")
        public List<String> tableColumnsName()
        {   
            List<String> Columns = new ArrayList<String>();
            Field[] fields = User.class.getDeclaredFields();
    
            for (Field field : fields) {
                Column col = field.getAnnotation(Column.class);
                if (col != null) {
                    Columns.add(col.name());
                    System.out.println("Columns: "+col);
                }
             }
              return Columns;   
        } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 2022-01-19
      • 1970-01-01
      • 2018-03-02
      • 2020-02-04
      • 2021-04-02
      • 1970-01-01
      相关资源
      最近更新 更多