首页 / 操作系统 / Linux / Hibernate 更新部分字段的实现
在Hibernate 中,有时我们只需要更新部分字段,此时如果使用update()方法,会将所有字段都更新,对于没有set的字段,就会设置成NULL,如果这些字段里面有非空的字段就会报错。解决的方法可以直接写HQL语句,但是如果字段较多,并且更新的字段是不确定的时候,直接写HQL语句就显得比较麻烦。另一种方法是在XML文件中设置dynamic-update="true",这样设置以后,只对set了的字段更新,没有set的字段就不会更新。<class name="com.hzhi.entity.Person" table="person" dynamic-update="true">还有一种有效的方法就是先根据需要更新的记录主键,找出这条记录,根据提交的参数set相应的字段,然后再update()。// 根据用户提交的ID找出person2
int id = person.getId();
Person person2 = xkmpService.findById(id);
// 设置需要更新的字段的值到person2
person2.setAge(person.getAge());
// 更新person2
xkmpService.updatePerson(person2);Hibernate3.1.2_中文文档PDF http://www.linuxidc.com/Linux/2016-02/128462.htmHibernate学习入门教程 http://www.linuxidc.com/Linux/2015-08/121498.htm在Hibernate中开启日志 http://www.linuxidc.com/Linux/2015-07/120499.htmHibernate+JUnit测试实体类生成数据库表 http://www.linuxidc.com/Linux/2015-07/120161.htmHibernate整体理解 http://www.linuxidc.com/Linux/2014-07/104405.htmHibernate的映射机制 http://www.linuxidc.com/Linux/2014-12/110265.htmHibernate 的详细介绍:请点这里
Hibernate 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-08/134362.htm