hibernate update单个字段

  Hibernate 中如果直接使用

 

  Session.update(Object o);

 

  会把这个表中的所有字段更新一遍。

 

  比如:

 

Xml代码   收藏代码
  1. public class TeacherTest {     
  2.     @Test    
  3.     public void update(){     
  4.         Session session =  HibernateUitl.getSessionFactory().getCurrentSession();     
  5.         session.beginTransaction();     
  6.         Teacher t = (Teacher) session.get(Teacher.class, 3);     
  7.         t.setName("yangtb2");     
  8.         session.update(t);     
  9.              
  10.         session.getTransaction().commit();     
  11.     }     
  12. }   

  Hibernate 执行的SQL语句:

 

Xml代码   收藏代码
  1. Hibernate:      
  2.     update     
  3.         Teacher      
  4.     set     
  5.         age=?,     
  6.         birthday=?,     
  7.         name=?,     
  8.         title=?      
  9.     where     
  10.         id=?    
  11. Hibernate:   
  12.     update  
  13.         Teacher   
  14.     set  
  15.         age=?,  
  16.         birthday=?,  
  17.         name=?,  
  18.         title=?   
  19.     where  
  20.         id=?   

 

 我们只更改了Name属性,而Hibernate 的sql语句 把所有字段都更改了一次。

 

  这样要是我们有字段是文本类型,这个类型存储的内容是几千,几万字,这样效率会很低。

   

  那么怎么只更改我们更新的字段呢?

 

  有三中方法:

 1.XML中设置property 标签 update = "false" ,如下:我们设置 age 这个属性在更改中不做更改

 

Xml代码   收藏代码
  1. <property name="age" update="false"></property>    
  2.      

 

  在Annotation中 在属性GET方法上加上@Column(updatable=false)

 

Java代码   收藏代码
  1. @Column(updatable=false)     
  2.     public int getAge() {     
  3.         return age;     
  4.     }    
  5.    

 

  我们在执行 Update方法会发现,age 属性 不会被更改

Java代码   收藏代码
  1. Hibernate:      
  2.     update     
  3.         Teacher      
  4.     set     
  5.         birthday=?,     
  6.         name=?,     
  7.         title=?      
  8.     where     
  9.         id=?    
  10.    

   缺点:不灵活····

  2.第2种方法··使用XML中的 dynamic-update="true"


 

Xml代码   收藏代码
  1. <class name="com.sccin.entity.Student"  table="student" dynamic-update="true">    
  2.     

  OK,这样就不需要在字段上设置了。

 

  但这样的方法在Annotation中没有

 

  3.第三种方式:使用HQL语句(灵活,方便)

 

  使用HQL语句修改数据

Java代码   收藏代码
  1. public void update(){  
  2.   Session session =  HibernateUitl.getSessionFactory().getCurrentSession();  
  3.   session.beginTransaction();  
  4.   Query query = session.createQuery("update Teacher t set t.name = 'yangtianb' where id = 3");  
  5.   query.executeUpdate();  
  6.   session.getTransaction().commit();  
  7.  }   
  8.    

 

  Hibernate 执行的SQL语句:

 

Java代码   收藏代码
  1. Hibernate:   
  2.     update  
  3.         Teacher   
  4.     set  
  5.         name='yangtianb'   
  6.     where  
  7.         id=3  
  8.    

  

这样就只更新了我们更新的字段······

转自:http://gerrard-ok.iteye.com/blog/703397

猜你喜欢

转载自wangxr66.iteye.com/blog/1829468