Hibernate 中如果直接使用
Session.update(Object o); 或则是Session.updateOrUpdate(Object o);
会把这个表中的所有字段更新一遍。
有三种方法:
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;
}
<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();
}
private boolean update(boolean isHql, String queryString, Map<String, Object> param) {
// TODO Auto-generated method stub
Query query = null;
if (isHql) {
query = this.getLocSession().createQuery(queryString);
} else {
query = this.getLocSession().createSQLQuery(queryString);
}
if (null != param && !param.isEmpty()) {
query.setProperties(param);
}
if(query.executeUpdate() > 0){
return true;
}
return false;
}