- 论坛徽章:
- 0
|
Hibernate批理更新与批量删除
批理修改:
场景:如有一个学生表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();
}
}
}
批量删除
场景:如有一个学生表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();
}
}
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/78176/showart_1226403.html |
|