如何使用hibernate模板使用hql update查询 thi是hql语句“update login set empSmartId = 48750005”+“where empPassword = 6328ef1675ddb7106eba8dc2661961d7”
使用getHibernatetemplate()
当前代码:
public class LoginDaoImp extends HibernateDaoSupport implements LoginDao {
public boolean resetAttempt(Login login) {
try { login.setAttempt(0);
getHibernateTemplate().update(login);
return true;
} catch (Exception e) { e.printStackTrace(); }
return false; }
i can save whole pojo class above code work but i want to use where condition to update only hibernateTemplate to update the data
答案 0 :(得分:0)
你会看起来像这样
public class LoginDaoImp extends HibernateDaoSupport implements LoginDao
{
public boolean resetAttempt(Login login)
{
try
{
// you should create method for login to retrived based on password
//Remember getting login by password is not correct way, Instead you you should use primary key
//Getting persisted object of Login
Login persisted_login = getLoginByPassword(6328ef1675ddb7106eba8dc2661961d7);
//Setting value in persisted object of Login
persisted_login.setEmpSmartId (48750005);
getHibernateTemplate().update(persisted_login);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
答案 1 :(得分:0)
我知道这个问题已经过时了,但这个解决方案是否有助于其他人......
这是更新数据库中记录的技巧。
技巧是首先从数据库中获取所需的记录,使用相关POJO类的放大器方法更新所需的字段。然后拨打hibernateTemplate.save(Object entity)
方法,如下所示: -
public void updateUser(User user, String password) {
@SuppressWarnings("unchecked")
List<User> results = (List<User>) hibernateTemplate
.find("FROM User where username = ?", new Object[] { new String(user.getUsername()) });
User userToBeUpdate = results.get(0);
userToBeUpdate.setPassword(password);
hibernateTemplate.save(userToBeUpdate);
}
这是我工作的解决方案。