使用列名获取实体中的字段名

To get the field name in an entity using column name

有什么方法可以使用列名获取实体中的字段名。

@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 name 有什么方法可以获取实体中的字段名称。这是它的 wCode。 我想用它来创建自定义 JPQL 查询。

您可以解析列注释:

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

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

@Column(name, columnDefinition, insertable, length, nullable, precision, scale, table, unique, updatable)

我们可以通过User.class.getDeclaredFields()(一般ModelName.class.getDeclaredFields())获取Entity中声明的所有字段。获取所有字段后,我们可以使用 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;   
    }