[英]How get specific columns of table and its foreign key as object using Java Hibernate and Criteria
Suppose I have an object User (with several properties) mapped in java spring using hibernate and the object Adress (also with several properties) where in the hbm.xml
file of User there is a many-to-one relationship with Address.
public class User{
Long id;
String name;
Integer age;
Address address;
}
public class Address{
Long id;
String description;
Integer number;
String state;
String country;
}
我想使用我只想獲取id, name
和唯一id, description, number
的條件進行查詢。
我已經嘗試過使用setProjection
,但是如果將id,name,address
放在投影列表中,它將從 Address 中獲取所有屬性,但我只想要一些針對性能問題的特定屬性。
Criteria criteria = createCriteria(User.class, "user");
criteria.setProjection(Projections.projectionList()
.add(Projections.property("user.id"),"id")
.add(Projections.property("user.name"),"name")
.add(Projections.property("user.address"),"address")
).setResultTransformer(Transformers.aliasToBean(User.class));
I'm using a older version of hibernate so it is using xml file to map the java object and the database table:
<class name="com.models.impl.User" table="USER">
<id name="id" column="USER_ID"></id>
...
<many-to-one lazy="false" name="address" class="com.models.impl.Address" >
<column name="ADDR_ID"/>
</many-to-one>
</class>
在這種情況下,通過用戶 ID 進行第二次查詢過濾地址(及其特定列)對我來說不是一個選項。 這樣我就必須打開另一個與數據庫的連接,因為我有一個超過三千行的查詢,所以兩個查詢的性能成本會非常高。
任何人都可以幫助我嗎?
謝謝你們
您使用的是哪個版本? 您必須加入地址關聯才能僅投影特定的字段/列,可能是這樣的:
Criteria criteria = createCriteria(User.class, "user");
criteria.setProjection(Projections.projectionList()
.add(Projections.property("user.id"),"id")
.add(Projections.property("user.name"),"name")
.add(Projections.property("user.address.number"),"addressNumber")
.add(Projections.property("user.address.state"),"addressState")
).setResultTransformer(Transformers.aliasToBean(User.class));
我不知道舊版 Hibernate 標准 API 的確切細節,但我認為有了這些信息,您應該能夠弄清楚:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.