Hibernate批量更新与批理删除
时间:2011-02-15
批理修改:
场景:如有一个学生表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();
}
}
}
Hibernate批量更新与批理删除(2)
时间:2011-02-15
批量删除
场景:如有一个学生表Student,现要删除学院为"技术学院"的学生.
用Hibernate实现这种批理删除的方法一DML(数据操作语言)操作。代码如下:
public void deleteUser(String deptName) {
Session session = null;
try{
session = this.getSession();
Transaction tc = session.beginTransaction();
String hqlUpdate = "delete from Student where deptName= :deptName";
int updatedEntities = s.createQuery( hqlUpdate )
.setString( "deptName", deptName)
.executeUpdate();
tc.commit();
}catch(RuntimeException re){
log.debug(re.getMessage(),re);
throw re;
}finally{
if (session != null){
session.close();
}
}
}
方法二绕过Hibernate API,用JDBC实现。
public void deleteUser(String deptName) {
Session session = null;
try{
session = this.getSession();
Transaction tc = session.beginTransaction();
Connection connection = session.connection();
PreparedStatement ps = connection.prepareStatement("delete from Student where deptName= ''"+deptName+"''");
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();
}
}
}
|