@DynamicInsert和@DynamicUpdate,Hibernate如何插入sysdate

@DynamicInsert属性:设置为true,设置为true,表示insert对象的时候,生成动态的insert语句,如果这个字段的值是null就不会加入到insert语句当中.默认false。

比如希望数据库插入日期或时间戳字段时,在对象字段为空的情况下,表字段能自动填写当前的sysdate。

@DynamicUpdate属性:设置为true,设置为true,表示update对象的时候,生成动态的update语句,如果这个字段的值是null就不会被加入到update语句中,默认false。

比如只想更新某个属性,但是却把整个对象的属性都更新了,这并不是我们希望的结果,我们希望的结果是:我更改了哪些字段,只要更新我修改的字段就够了。

 

@DynamicInsert

写了个main程序测试:代码如下:

  • 数据库DDL语句:
1 create table CAT
2 (
3   id          VARCHAR2(32) not null,
4   CAT_NAME    VARCHAR2(32) default sysdate,
5   create_time DATE,
6   update_time DATE
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 
 6 <hibernate-configuration>
 7     <session-factory>
 8         <!-- 数据库驱动配置 -->
 9         <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
10         <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
11         <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
12         <property name="connection.username">wxuatuser</property>
13         <property name="connection.password">xlh</property>
14         <property name="show_sql">true</property>
15         
16         <!-- hibernate实体类 -->
17         <mapping class="test2.Cat"/>
18     </session-factory>
19 </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     }
38 
39 
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 
57 
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 test2;
 2 import javax.persistence.Entity;
 3 import model.BaseEntity;
 4 import org.hibernate.annotations.DynamicInsert;
 5 
 6 @Entity
 7 @DynamicInsert
 8 public class Cat extends BaseEntity{
 9     /**
10      * 实体类
11      */
12     private static final long serialVersionUID = -2776330321385582872L;
13     
14     private String cat_name;
15 
16     public String getCat_name() {
17         return cat_name;
18     }
19 
20     public void setCat_name(String cat_name) {
21         this.cat_name = cat_name;
22     }
23 }

main入口
 1 package test2;
 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 import test2.Cat;
11 
12 public class HibernateUtil {
13 
14     private static final SessionFactory sessionFactory;
15 
16     static {
17         try {
18             Configuration cfg = new Configuration().configure();
19             ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
20                     .applySettings(cfg.getProperties()).buildServiceRegistry();
21             sessionFactory = cfg.buildSessionFactory(serviceRegistry);
22         } catch (Throwable ex) {
23             // Log exception!
24             throw new ExceptionInInitializerError(ex);
25         }
26     }
27 
28     public static Session getSession() throws HibernateException {
29         return sessionFactory.openSession();
30     }
31 
32     public static void main(String[] args) {
33         Session session = HibernateUtil.getSession();
34         Transaction tx = null;
35         try {
36             tx = session.beginTransaction();
37             Cat cat = new Cat();
38             cat.setCat_name("cat@DynamicInsert");
39             session.save(cat);
40             tx.commit();
41         } catch (RuntimeException e) {
42             if (tx != null) {
43                 tx.rollback();
44             }
45             throw e;
46         } finally {
47             session.close();
48         }
49     }
50 }

@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类
实体类:Cat 同上。

main入口
 1 package test2;
 2 
 3 import java.util.Date;
 4 
 5 import org.hibernate.HibernateException;
 6 import org.hibernate.Session;
 7 import org.hibernate.SessionFactory;
 8 import org.hibernate.Transaction;
 9 import org.hibernate.cfg.Configuration;
10 import org.hibernate.service.ServiceRegistry;
11 import org.hibernate.service.ServiceRegistryBuilder;
12 
13 public class HibernateUtil_DynamicUpdate {
14 
15     private static final SessionFactory sessionFactory;
16 
17     static {
18         try {
19             Configuration cfg = new Configuration().configure();
20             ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
21                     .applySettings(cfg.getProperties()).buildServiceRegistry();
22             sessionFactory = cfg.buildSessionFactory(serviceRegistry);
23         } catch (Throwable ex) {
24             // Log exception!
25             throw new ExceptionInInitializerError(ex);
26         }
27     }
28 
29     public static Session getSession() throws HibernateException {
30         return sessionFactory.openSession();
31     }
32 
33     public static void main(String[] args) {
34         Session session = HibernateUtil_DynamicUpdate.getSession();
35         Transaction tx = null;
36         try {
37             tx = session.beginTransaction();
38             Cat cat = (Cat)session.get(Cat.class, "8a6cc5a34c456829014c45682a860000");
39             cat.setUpdate_time(new Date());
40             cat.setCat_name("test@555");
41             session.update(cat);
42             tx.commit();
43         } catch (RuntimeException e) {
44             if (tx != null) {
45                 tx.rollback();
46             }
47             throw e;
48         } finally {
49             session.close();
50         }
51     }
52 }

 

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%40DynamicUpdate.rar

环境:JDK1.6,MAVEN

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。