开发者

Make use of Hibernate attribute mapping in plain SQL query

开发者 https://www.devze.com 2023-02-04 14:57 出处:网络
Is there any way to let Hibernate replace entity attribute names in a native SQL query (created by Session.createSQLQuery())?

Is there any way to let Hibernate replace entity attribute names in a native SQL query (created by Session.createSQLQuery())?

I would like to build a query where arbitrary columns are fetched which do not result in a Hibernate entity, similar to this one

SELECT t1.attr1, t2.attr2, t3.attr3 WHERE t1.attr1 = 'foo' AND t2.attr2 = ...
开发者_开发知识库

with "attr1", "attr2",... being Java property names which should be automatically mapped by Hibernate.

I've seen SQLQuery.addEntity() but that seems to work on the result set, not on the query.

Is there any way to replace attribute names on a query, or any tool which allows me to easily access the mappings generated by Hibernate without having to check the annotations on an entity myself?

Thanks!


If the only need to use SQL query is to fetch separate columns instead of the full entity, you can express such a query in HQL as well. Tuple of column values will be returned as Object[]:

Object[] tuple = s.createQuery("SELECT t.a, t.b, t.c FROM SomeEntity t WHERE ...").uniqueResult();


If you use a custom NamingStrategy (or a standard one, for that matter), you can use the NamingStrategy class to generate your column names from property names.

NamingStrategy namingStrategy = new DefaultNamingStrategy();
String yourPropertyName="fooBar";
String columnName = namingStrategy.propertyToColumnName(yourPropertyName);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号