How to retrieve a member object of a class using Hibernate?

痴心易碎 提交于 2019-12-04 13:31:42

Use JPQL/HQL:

select a from User u join u.address a where u.id = :userId

The Criteria API is more limited than JPQL, and can't select any other entity than the root entity. It shouldn't be used if the query doesn't have to be dynamically composed. Of course, if the association is bidirectional, you can simply use

select a from Address a where a.user.id = :userId

or its equivalent Criteria:

Criteria c = session.createCriteria(Address.class, "a");
c.createAlias("a.user", "u");
c.add(Restrictions.eq("u.id", userId));

If the result you pull in from a query will match the fields of a DAO you have defined. I would just type-cast the result from an hql or native SQL query.

Select  * 
From Address a
where a.id = :userid

Address addrObject = (Address) query.uniqueResult();

Do like this

 Criteria criteria = session.createCriteria(User.class, "user")
              .createAlias("user.address", "addr")          
             .add(Restrictions.eq("user.id", userId))            
             .setProjection(Projections.property("addr"));

 Address address = (Address) criteria.list().get(0);

Couple of options:

  1. use lazy="false" for Address object. If you have to use lazy=true for some reason, you can run this query in a separate session and override the lazy behavior in that session.
  2. Use the database specific query to get a list of field names and then dynamically generate Projections by looping through the field names.

For example, In mysql

SHOW COLUMNS FROM Address

In postgres

SELECT * FROM information_schema.columns
WHERE table_schema = your_schema
AND table_name   = your_table

I hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!