简体   繁体   中英

working with object with spring and hibernate

hope everybody is cool.I've been trying to do something with spring-hibernate but it's still a failure.i'm very new to it.i need a little help.supposing a POJO class Users.i want to return an Users object by username.While i had no problem to return Users object by id by doing this

   return (Users) getHibernateTemplate().get(Users.class, id);

it seems to be a challenge for me getting the Users object by username. I've tried this

List<Users> users = getHibernateTemplate().find("from Users u where u.username=?",username);
return  users.get(0);

and even this

return (Users)getHibernateTemplate().find("from Users u where u.username=?",username).get(0);

how should i do it.And what is the proper way to return an array of Users objects and/or List.Thanks for reading this.

Try this

Query q = session.createQuery("select * from Users u where u.username=:username");
q.setString("username", username);

maybe you can try this?

List l =getHibernateTemplate().find("from Users u where u.username=?",new Object[]{username});
if (l.size() > 0)
 return (User)l.get(0);
else
return null;

Another better way is to use Criteria. See the example below.

    DetachedCriteria deCriteria = DetachedCriteria.forClass(User.class, "u");
    Criteria criteria = deCriteria.getExecutableCriteria(session);

    criteria.add(Restrictions.eq("u.username", username));
    List<User> userList = criteria.list();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM