英文:
How to change column alias in entity definition, that is used in HQL queries in Hibernate?
问题
我正在尝试弄清楚如何在HQL中更改列名的别名,就像我们可以使用@Entity(name = "example")
注解更改实体名别名一样。
例如,假设我们有这样一个实体类:
@Entity(name = "example")
@Table(name = "example")
public class Example {
public Example(String exampleField) {
this.exampleField = exampleField;
}
@Id
@GeneratedValue
@Column(name = "id")
public Long id;
@Column(name = "example_field")
public String exampleField;
}
在HQL中按字段名选择有效:
entityManager.createQuery("select e.exampleField from example e")
如何使得在HQL中选择自定义列名成为可能,就像这样?
entityManager.createQuery("select e.example_field from example e")
请注意,第二个(虽然不起作用,但首选)示例中的别名为example_field
,而不是exampleField
。
英文:
I'm trying to figure out how to change column name alias used in HQL, like we can change entity name alias with @Entity(name = "example")
annotation.
Say for example we have such entity class:
@Entity(name = "example")
@Table(name = "example")
public class Example {
public Example(String exampleField) {
this.exampleField = exampleField;
}
@Id
@GeneratedValue
@Column(name = "id")
public Long id;
@Column(name = "example_field")
public String exampleField;
}
Selecting by field name in HQL works:
entityManager.createQuery("select e.exampleField from example e")
How to make possible selecting by customized column name in HQL, like this?
entityManager.createQuery("select e.example_field from example e")
Notice, the second (not working, but preferred) example has example_field
instead of exampleField
答案1
得分: 1
JPA不定义指定持久属性别名的方法,Hibernate(特别是在提到HQL时)也没有为此提供扩展。如果您使用基于字段的访问,就像您的示例中一样,在HQL查询中,您必须通过它们的字段名称引用实体属性。另一方面,如果您使用基于属性的访问,那么您必须通过从注释的访问器方法的名称派生的名称引用实体属性。没有@Entity
注解的name
属性的字段级别类似物。
如何在HQL中选择自定义列名
只需在Java端将字段命名为您想在查询中引用的任何名称。例如,
@Column(name = "example_field")
public String example_field;
如果您恰好受制于不允许使用这种字段名称的Java编码约定,那么您将受限制。无法满足这些约定并在HQL查询中以您喜欢的名称引用字段。
英文:
JPA does not define any way to specify an alias for a persistent property, nor does Hibernate (since you mention HQL in particular) offer an extension for that purpose. If you use field-based access, as in your example, then in your HQL queries, you must refer to entity attributes via their field names. On the other hand, if you use property-based access then you must refer to entity attributes via names derived from the names of the annotated accessor methods. There is no field-level analogue of the name
attribute of the @Entity
annotation.
> How to make possible selecting by customized column name in HQL
Only by naming the field on the Java side with whatever name you want to use to refer to it in your queries. For example,
@Column(name = "example_field")
public String example_field;
If you happen to be subject to Java coding conventions that disallow such field names then you're stuck. There is no way to satisfy such conventions and also refer to the fields by the names you prefer in your HQL queries.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论