問題:設置了dynamic-update, 可是事實上並沒有按照期望進行了update。
案例代碼如下:
1、持久化對象
1 package com.jdw.hibernate.entities; 2 3 import java.util.Date; 4 5 public class News { 6 private Integer id; 7 private String title; 8 private String author; 9 private Date date; 10 11 public News() { 12 // TODO Auto-generated constructor stub 13 } 14 15 public News(String title, String author, Date date) { 16 super(); 17 this.title = title; 18 this.author = author; 19 this.date = date; 20 } 21 22 @Override 23 public String toString() { 24 return "News [id=" + id + ", title=" + title + ", author=" + author 25 + ", date=" + date + "]"; 26 } 27 28 public Integer getId() { 29 return id; 30 } 31 32 public void setId(Integer id) { 33 this.id = id; 34 } 35 36 public String getTitle() { 37 return title; 38 } 39 40 public void setTitle(String title) { 41 this.title = title; 42 } 43 44 public String getAuthor() { 45 return author; 46 } 47 48 public void setAuthor(String author) { 49 this.author = author; 50 } 51 52 public Date getDate() { 53 return date; 54 } 55 56 public void setDate(Date date) { 57 this.date = date; 58 } 59 } View Code2、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臨時對象不起作用。至於為什麼這麼設計?求高人告之。