批理修改:
場景:如有一個學生表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();
}
}
}