刚刚开始学习spring,持久层用hibernate,
在程序里面我需要修改用户信息的密码字段,
(User)this.getHibernateTemplate().get(User.class, userNo);
user.setPassword(newPassword);
this.getHibernateTemplate().merge(user);
如果我不想先把用户信息全取出来,然后修改密码字段放进去,有什么其他的方法吗?
给点建议 呵呵
问题补充:
谢谢wangxuliangboy
session.createQuery(sql).setString("password",password).setString("userNo",userNo).executeUpdate();
这一句里面如果传入用户的变量无法通过
public class UserInfoDAO extends HibernateDaoSupport{
public void updateUserInfo(User user){
String sql="update User set password = :password where userNo = :userNo";
Query query=this.getSession().createQuery("");
query.setString("password",user.getPassword()).
query.setString("userNo",user.getUserNo()).
query.executeUpdate();
}
}
如果这样写需要在方法里面加这个吗
Transaction t=session.beginTransaction();
如果传入用户的变量无法通过 ,为什么无法通过..如果是在内问类调用的话..你要申明成FINAL的才行
如果你只是想更新的话...你没必要查询出这个User对象.
Session session =sessionFactory.openSession();
Transaction t=session.beginTransaction();
String sql="update User set password = :password where userNo = :userNo";
session.createQuery(sql).setString("password",password).setString("userNo",userNo).executeUpdate();
hibernateTemplate可以这样用:
return this.hibernateTemplate.execute(new HibernateCallback() {
public Object doInHibernate(Session session) {
Transaction t=session.beginTransaction();
String sql="update User set password = :password where userNo = :userNo";
session.createQuery(sql).setString("password",password).setString("userNo",userNo).executeUpdate();
}
};
你继承了HibernateDaoSupport,但是不知道你有没有配置spring的声明式事务..如果声明了,被正确的配置了..就可以不要用Transaction t=session.beginTransaction();