[转]用Hibernate查询部分字段

How to query several columns with Hibernate?

Even though Hibernate is called an  object-relational mapper it's easy to select only a few properties instead of the whole mapped object. The hibernate query language (HQL) is very expressive. If you select some properties instead of the whole object, the call of  Query#list()returns a list of object arrays. Each field of the array contains one of the selected properties.



1. select c.name, c.order
2. from Customer c

In my opinion iterating over lists of  Object[] is verbose and error-prone because processing the result-list is directly dependant on the sequence of selected properties in the hql string. If you change the query string you have to change the sourcecode as well.
Did I mention how expressive HQL is? :) Check out the following snippet:
1. select new map(c.name as name, c.order as order)
2. from Customer c

Instead of returning arrays this query will return a list of maps each containing entries with aliases (the keys) to selected values.
Actually it's possible to let Hibernate return partially loaded entities instead of maps containing the properties of interest. Check out the following example:
1. select new Customer(c.name, c.order)
2. from Customer c

This query will return lists of customers assuming there is an appropriate constructor.

You should really pay attention with this approach of partially loaded entities because updating these entities could lead to accidently loosing data.
From: http://bwinterberg.blogspot.hk/2009/08/how-to-query-several-properties-with.html

猜你喜欢

转载自kingsleylong.iteye.com/blog/1559651
今日推荐