- 0
- 0
- 约3.31千字
- 约 5页
- 2017-02-09 发布于重庆
- 举报
Hibernate更新某些字段的几种update方法
Hibernate更新某些字段的几种update方法
(2011-02-18 11:33:48)
转载
标签:
更改
语句
属性
方法
it 分类: Hibernate 中如果直接使用
Session.update(Object o);
会把这个表中的所有字段更新一遍。
比如:
view plaincopy to clipboardprint?public class TeacherTest {????? @Test??? public void update(){????????? Session session = HibernateUitl.getSessionFactory().getCurrentSession();????????? session.beginTransaction();????????? Teacher t = (Teacher) session.get(Teacher.class, 3);????????? t.setName(yangtb2);????????? session.update(t);??????????????????? session.getTransaction().commit();????? }??}public class TeacherTest {@Testpublic void update(){?? Session session = HibernateUitl.getSessionFactory().getCurrentSession();?? session.beginTransaction();?? Teacher t = (Teacher) session.get(Teacher.class, 3);?? t.setName(yangtb2);?? session.update(t);???? session.getTransaction().commit();}}
Hibernate 执行的SQL语句:
view plaincopy to clipboardprint?Hibernate:?????? update????????? Teacher?????? set????????? age=?,????????? birthday=?,????????? name=?,????????? title=??????? where????????? id=?Hibernate:??? update??????? Teacher??? set??????? age=?,??????? birthday=?,??????? name=?,??????? title=???? where??????? id=?
我们只更改了Name属性,而Hibernate 的sql语句 把所有字段都更改了一次。
这样要是我们有字段是文本类型,这个类型存储的内容是几千,几万字,这样效率会很低。
那么怎么只更改我们更新的字段呢?
有三中方法:
1.XML中设置property 标签 update = false ,如下:我们设置 age 这个属性在更改中不做更改
view plaincopy to clipboardprint?property name=age update=false/propertyproperty name=age update=false/property
在Annotation中 在属性GET方法上加上@Column(updatable=false)
view plaincopy to clipboardprint?@Column(updatable=false)????? public int getAge() {????????? return age;????? }@Column(updatable=false)public int getAge() {?? return age;}
我们在执行 Update方法会发现,age 属性 不会被更改
view plaincopy to clipboardprint?Hibernate:?????? update????????? Teacher?????? set????????? birthday=?,????????? name=?,????????? title=??????? where????????? id=?Hibernate:??? update??????? Teacher??? set??????? birthday=?,???
原创力文档

文档评论(0)