Hibernate 中如果直接使用 BaiscDao中的update() 会更新所有字段,不管改没改与否,都会更新。
如何做到只更新 自己更改过得字段,其他字段不更改。
有三种方法:
1.XML中设置property 标签 update = "false" ,如下:我们设置 age 这个属性在更改中不做更改
<property name="age" update="false"></property>
在Annotation中 在属性GET方法上加上@Column(updatable=false)
@Column(updatable=false)
public int getAge() {
return age;
}
2.使用XML中的 dynamic-update="true"
<class name="com.sccin.entity.Student" table="student" dynamic-update="true">
OK,这样就不需要在字段上设置了。
但这样的方法在Annotation中没有
3.使用HQL语句(灵活,方便)
使用HQL语句修改数据
public void update(){
Session session = HibernateUitl.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("update Teacher t set t.name = 'yangtianb' where id = 3");
query.executeUpdate();
session.getTransaction().commit();
}