问题:设置了dynamic-update, 可是事实上并没有按照期望进行了update。
案例代码如下:
1、持久化对象
package com.jdw.hibernate.entities; import java.util.Date; public class News {
private Integer id;
private String title;
private String author;
private Date date; public News() {
// TODO Auto-generated constructor stub
} public News(String title, String author, Date date) {
super();
this.title = title;
this.author = author;
this.date = date;
} @Override
public String toString() {
return "News [id=" + id + ", title=" + title + ", author=" + author
+ ", date=" + date + "]";
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public String getAuthor() {
return author;
} public void setAuthor(String author) {
this.author = author;
} public Date getDate() {
return date;
} public void setDate(Date date) {
this.date = date;
}
}
2、hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-3-8 20:08:39 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.jdw.hibernate.entities.News" table="NEWS" lazy="false" select-before-update="true" dynamic-update="true">
<id name="id" type="java.lang.Integer" unsaved-value="110">
<column name="ID" />
<generator class="native" />
</id>
<property name="title" type="java.lang.String">
<column name="TITLE" />
</property>
<property name="author" type="java.lang.String">
<column name="AUTHOR" />
</property>
<property name="date" type="java.util.Date">
<column name="DATE" />
</property>
</class>
</hibernate-mapping>
3、测试代码
@Test
public void testDynamicUpdate() {
News news =new News(); news.setAuthor("test");//注意:这里只设置了test属性
news.setId(13); session.update(news);
}
4、结果
Hibernate:
select
news_.ID,
news_.TITLE as TITLE2_1_,
news_.AUTHOR as AUTHOR3_1_,
news_.DATE as DATE4_1_
from
NEWS news_
where
news_.ID=?
Hibernate:
update
NEWS
set
TITLE=?,
AUTHOR=?,
DATE=?
where
ID=?
hibernate并没有按照期望只update Author属性,而是更新了所有属性,其他属性肯定更新成了null,坏菜了!
网上查了资料,不少同学说要在设置dynamic-update的同时,设置select-before-update即可满足期望,注意上面的映射文件,是设置了该属性的。
那问题出在哪里?如何解决呢?
--------------------------------------------------------------------------------
先看另一段测试代码:
@Test
public void testDynamicUpdate2() {
News news =(News) session.get(News.class, 13); news.setAuthor("test");//注意:这里只设置了test属性 session.update(news);
}
结果如你所愿,只更新了author字段。两项比较,dynamic-update=true,只对持久化对象起作用,对于transient临时对象不起作用。至于为什么这么设计?求高人告之。