Hibernate 更新部分更改的字段 hibernate update

原文地址为: Hibernate 更新部分更改的字段 hibernate update

Hibernate 中如果直接使用 

Session.update(Object o); 或则是Session.updateOrUpdate(Object o); 

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

 如:

ExperClass4k e = new ExperClass4k();
			e.setTime(time);
			e.setQ_num(q_num);
			e.setK(k);
			if (str == "finch_fix") {
				e.setFinch_fix_cost1(cost1);
				e.setFinch_fix_cost2(cost2);
				e.setFinch_fix_cost(cost1 + cost2);
			} else if (str == "my") {
				e.setMy_cost1(cost1);
				e.setMy_cost2(cost2);
				e.setMy_cost(cost1 + cost2);
				}
			//session.save(e);
			session.saveOrUpdate(e);
我本想根据str判断,做出不同的更新策略,但是对于同一个time,Hibernate 的sql语句把所有字段都更改了一次(没有被set的值,Hibernate会直接赋值空)。

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

 

有三种方法:

 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();
	}







转载请注明本文地址: Hibernate 更新部分更改的字段 hibernate update

猜你喜欢

转载自blog.csdn.net/wcqlwyt/article/details/80732279