• Hibernate,JPA注解@DynamicInsert和@DynamicUpdate,Hibernate如何插入sysdate


    @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

  • 相关阅读:
    Windows Server 2008 R2系统上安装SQLServer2012集群(简略)
    播放视频有沙沙的杂音怎么处理?
    合并两个表取数
    电脑下边的语言栏跑到左边了怎么办?
    一条SQL查出当月的每一天
    统一本地服务器名和计算机名
    一个奇葩的SQL
    Cent Os7.0安装MongoDB4.2.0
    MySQL 8.0.5开启远程连接
    MySQL系统函数及SQL开发中易犯错的点
  • 原文地址:https://www.cnblogs.com/xiluhua/p/4359823.html
Copyright © 2020-2023  润新知