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 {
@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();
}
}
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?
在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=?,
name=?,
title=?
where
id=?
缺点:不灵活····
2.第2种方法··使用xml中的 dynamic-update=”true”
view plaincopy to clipboardprint?
ok,这样就不需要在字段上设置了。
但这样的方法在annotation中没有
3.第三种方式:使用hql语句(灵活,方便)
使用hql语句修改数据
view plaincopy to clipboardprint?
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();
}
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 执行的sql语句:
view plaincopy to clipboardprint?
hibernate:
update
teacher
set
name=’yangtianb’
where
id=3
hibernate:
update
teacher
set
name=’yangtianb’
where
id=3
这样就只更新了我们更新的字段······