批理修改:
场景:如有一个学生表Student,现有一属性[学院]改名,从"计算机学院"改为"计算机工程学院"[不考虑学院表].
用Hibernate实现这种批理更新的方法一DML(数据操作语言)操作。代码如下:
public void updateUser(String newName,String oldName) {
Session session = null;
try{
session = this.getSession();
Transaction tc = session.beginTransaction();
String hqlUpdate = "update Student set deptName=:newName where deptName= :oldName";
int updatedEntities = s.createQuery( hqlUpdate )
.setString( "newName", newName )
.setString( "oldName", oldName )
.executeUpdate();
tc.commit();
}catch(RuntimeException re){
log.debug(re.getMessage(),re);
throw re;
}finally{
if (session != null){
session.close();
}
}
}
方法二绕过Hibernate API,用JDBC实现。
public void UpdateUser(String newName,String oldName) {
Session session = null;
try{
session = this.getSession();
Transaction tc = session.beginTransaction();
Connection connection = session.connection();
PreparedStatement ps = connection.prepareStatement("update Student set deptName='"+newName+"' where deptName= '"+oldName+"'");
ps.execute();
tc.commit();
}catch(RuntimeException re){
log.debug(re.getMessage(),re);
throw re;
}catch(SQLException e){
log.debug(e.getMessage(),e);
}finally{
if (session != null){
session.close();
}
}
}