开发者

How do I use a custom select statement in Hibernate using the HibernateDaoSupport class

开发者 https://www.devze.com 2022-12-27 15:54 出处:网络
I am trying to write a custom select statement in Hibernate using the getHibernateTemplate() method.I am having problems with the resulting mapping.

I am trying to write a custom select statement in Hibernate using the getHibernateTemplate() method. I am having problems with the resulting mapping.

Example Code:

List<User> users = getHibernateTemplate().find("Select user, sysdate as latestPost from User as user");
for (User user : users) {
assertNotNull(users.name);
}

The goal of the above line is to eventually have a join where I get the max(date) of posts made开发者_高级运维 by the user. The problem I am having is that the resulting users list is not a list of User objects and I get a class cast exception.

Hopefully that is enough code. It is a greatly simplified version of my problem and a combination of snippets from various parts of my application.


Figured this out. I am already using a HibernateDaoSupport derived DAO class so this solution goes along with that.

String queryString = "Select {user.*}, (select max(submitted) from posts where post.user_id = user.id) MAX_POST from users user";
SQLQuery query = getSession().createSQLQuery(queryString);
query.addEntity("user", User.class);
query.addScalar("MAX_POST", Hibernate.DATE);

List results = query.list();
List<User> users = new ArrayList();
for (Object item : results) {
    Object[] element = (Object[]) item; 
    User user = (User)element[0];
    user.setMaxPost((Date)element[1]);
    users.add(user);
}

The above example is greatly simplified but should show a method you can use to solve this problem. I actually was able to include one of my EAGER fetches by incorporating into the SQL the neccessary tables and then use the addJoin method


Sounds like Hibernate isn't want you want here. Maybe you should start with SimpleJDBCTemplate and a RowMapper and build up from there.

0

精彩评论

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