@DynamicInsert屬性:設置為true,設置為true,表示insert對象的時候,生成動態的insert語句,如果這個字段的值是null就不會加入到insert語句當中.默認false。
比如希望數據庫插入日期或時間戳字段時,在對象字段為空的情況下,表字段能自動填寫當前的sysdate。
@DynamicUpdate屬性:設置為true,設置為true,表示update對象的時候,生成動態的update語句,如果這個字段的值是null就不會被加入到update語句中,默認false。
比如只想更新某個屬性,但是卻把整個對象的屬性都更新了,這並不是我們希望的結果,我們希望的結果是:我更改了哪些字段,只要更新我修改的字段就夠了。
@DynamicInsert
用例代碼如下:
- 數據庫DDL語句:
1 create table CAT 2 ( 3 id VARCHAR2(32 CHAR) not null, 4 create_time TIMESTAMP(6) default sysdate, 5 update_time TIMESTAMP(6), 6 cat_name VARCHAR2(255 CHAR) 7 )
- hibernate.cfg.xml
1 <?xml version="1.0" encoding="utf-8" ?> 2 <!DOCTYPE hibernate-configuration 3 PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory> 7 <!-- 數據庫驅動配置 --> 8 <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> 9 <property name="connection.driver_class">oracle.jdbc.OracleDriver</property> 10 <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property> 11 <property name="connection.username">wxuatuser</property> 12 <property name="connection.password">xlh</property> 13 <property name="show_sql">true</property> 14 <!-- 自動執行DDL屬性是update,不是true --> 15 <property name="hbm2ddl.auto">update</property> 16 <!-- hibernate實體類 --> 17 18 <mapping class="a2_DynamicInsert_Update.Cat"/> 19 20 </session-factory> 21 </hibernate-configuration>
- java類
實體類 - 基類
1 package model; 2 3 import java.io.Serializable; 4 import java.util.Date; 5 import javax.persistence.Column; 6 import javax.persistence.GeneratedValue; 7 import javax.persistence.Id; 8 import javax.persistence.MappedSuperclass; 9 import org.hibernate.annotations.GenericGenerator; 10 11 /** 12 * 實體類 - 基類 13 */ 14 @MappedSuperclass 15 public class BaseEntity implements Serializable { 16 17 private static final long serialVersionUID = -6718838800112233445L; 18 19 private String id;// ID 20 private Date create_time;// 創建日期 21 private Date update_time;// 修改日期 22 @Id 23 @Column(length = 32, nullable = true) 24 @GeneratedValue(generator = "uuid") 25 @GenericGenerator(name = "uuid", strategy = "uuid") 26 public String getId() { 27 return id; 28 } 29 30 public void setId(String id) { 31 this.id = id; 32 } 33 34 @Column(updatable = false) 35 public Date getCreate_time() { 36 return create_time; 37 } 40 public void setCreate_time(Date create_time) { 41 this.create_time = create_time; 42 } 43 44 public Date getUpdate_time() { 45 return update_time; 46 } 47 48 public void setUpdate_time(Date update_time) { 49 this.update_time = update_time; 50 } 51 52 @Override 53 public int hashCode() { 54 return id == null ? System.identityHashCode(this) : id.hashCode(); 55 } 56 58 @Override 59 public boolean equals(Object obj) { 60 if (this == obj) { 61 return true; 62 } 63 if (obj == null) { 64 return false; 65 } 66 if (getClass().getPackage() != obj.getClass().getPackage()) { 67 return false; 68 } 69 final BaseEntity other = (BaseEntity) obj; 70 if (id == null) { 71 if (other.getId() != null) { 72 return false; 73 } 74 } else if (!id.equals(other.getId())) { 75 return false; 76 } 77 return true; 78 } 79 }
實體類
1 package a2_DynamicInsert_Update; 2 import javax.persistence.Entity; 3 import model.BaseEntity; 4 import org.hibernate.annotations.DynamicInsert; 5 import org.hibernate.annotations.DynamicUpdate; 6 7 @Entity 8 @DynamicInsert 9 @DynamicUpdate 10 public class Cat extends BaseEntity{ 11 /** 12 * 實體類 13 */ 14 private static final long serialVersionUID = -2776330321385582872L; 15 16 private String cat_name; 17 18 public String getCat_name() { 19 return cat_name; 20 } 21 22 public void setCat_name(String cat_name) { 23 this.cat_name = cat_name; 24 } 25 }
Dao
1 package daoUtil; 2 3 import org.hibernate.HibernateException; 4 import org.hibernate.Session; 5 import org.hibernate.SessionFactory; 6 import org.hibernate.Transaction; 7 import org.hibernate.cfg.Configuration; 8 import org.hibernate.service.ServiceRegistry; 9 import org.hibernate.service.ServiceRegistryBuilder; 10 11 public class HibernateUtil { 12 13 private static final SessionFactory sessionFactory; 14 15 static { 16 try { 17 Configuration cfg = new Configuration().configure(); 18 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() 19 .applySettings(cfg.getProperties()).buildServiceRegistry(); 20 sessionFactory = cfg.buildSessionFactory(serviceRegistry); 21 } catch (Throwable ex) { 22 // Log exception! 23 throw new ExceptionInInitializerError(ex); 24 } 25 } 26 27 public static Session getSession() throws HibernateException { 28 return sessionFactory.openSession(); 29 } 30 31 public static Object save(Object obj){ 32 Session session = HibernateUtil.getSession(); 33 Transaction tx = null; 34 try { 35 tx = session.beginTransaction(); 36 session.save(obj); 37 tx.commit(); 38 } catch (RuntimeException e) { 39 if (tx != null) { 40 tx.rollback(); 41 } 42 throw e; 43 } finally { 44 session.close(); 45 } 46 return obj; 47 } 48 49 public static void delete(Class<?> clazz,String id){ 50 Session session = HibernateUtil.getSession(); 51 Transaction tx = null; 52 try { 53 tx = session.beginTransaction(); 54 Object obj = session.get(clazz,id); 55 session.delete(obj); 56 tx.commit(); 57 } catch (RuntimeException e) { 58 if (tx != null) { 59 tx.rollback(); 60 } 61 throw e; 62 } finally { 63 session.close(); 64 } 65 } 66 }
main
1 package a2_DynamicInsert_Update; 2 import a2_DynamicInsert_Update.Cat; 3 import daoUtil.HibernateUtil; 4 5 public class Test_DynamicInsert { 6 7 public static void main(String[] args) { 8 Cat cat = new Cat(); 9 cat.setCat_name("test2@DynamicInsert"); 10 HibernateUtil.save(cat); 11 } 12 }
@DynamicInsert注解下Hibernate日志打印SQL:
Hibernate: insert into Cat (cat_name, id) values (?, ?)
反之
Hibernate: insert into Cat (create_time, update_time, cat_name, id) values (?, ?, ?, ?)
@DynamicUpdate
寫了個main程序測試:代碼如下:
- 數據庫DML語句:
insert into CAT (ID, CAT_NAME, CREATE_TIME, UPDATE_TIME) values ('8a6cc5a34c456829014c45682a860000', 'test@555', SYSDATE, SYSDATE);
- hibernate.cfg.xml 同上
- java類
實體類,Dao 同上。
main
1 package a2_DynamicInsert_Update; 2 import org.hibernate.Session; 3 import org.hibernate.Transaction; 4 import daoUtil.HibernateUtil; 5 6 public class Test_DynamicUpdate { 7 8 public static void main(String[] args) { 9 Session session = HibernateUtil.getSession(); 10 Transaction tx = null; 11 try { 12 tx = session.beginTransaction(); 13 Cat cat = (Cat)session.get(Cat.class, "8a6cc5a34c6e7f32014c6e7f33500000"); 14 cat.setCat_name("test@DynamicUpdate"); 15 tx.commit(); 16 } catch (RuntimeException e) { 17 if (tx != null) { 18 tx.rollback(); 19 } 20 throw e; 21 } finally { 22 session.close(); 23 } 24 25 } 26 }
Cat實體類@DynamicUpdate注解下Hibernate日志打印SQL:
說明:如果字段有更新,Hibernate才會對該字段進行更新
Hibernate: update Cat set update_time=? where id=?
反之Cat實體類去掉@DynamicUpdate
說明:不管字段有沒有更新,Hibernate都會對該字段進行更新
Hibernate: update Cat set update_time=?, cat_name=? where id=?
Hibernate在執行更新操作前,會比對一下當前Session上下文中的對象與需要更新的對象數據是否一致,也就是說會確認數據有沒有變化,沒變化的話,無論寫多少次session.update(cat),都不會執行更新操作。
源碼地址:http://files.cnblogs.com/files/xiluhua/hibernate%40DynamicInsert_Update.rar
環境:JDK1.6,MAVEN