首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > PowerDesigner >

Hibernate更新某些字段的几种update步骤

2012-06-28 
Hibernate更新某些字段的几种update方法view plaincopy to clipboardprint?property nameage update

Hibernate更新某些字段的几种update方法

view plaincopy to clipboardprint?
<property name="age" update="false"></property>
<property 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=?,
??????? name=?,
??????? title=?
??? where
??????? id=?

缺点:不灵活····

2.第2种方法··使用XML中的 dynamic-update="true"

view plaincopy to clipboardprint?
<class name="com.sccin.entity.Student" table="student" dynamic-update="true">
<class name="com.sccin.entity.Student" table="student" dynamic-update="true">

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

这样就只更新了我们更新的字段······

热点排行