1. 首先创建\META-INF\persistence.xml配置文件并做简单的配置

    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
                version="2.0">

       <persistence-unit name="org.hibernate.tutorial.envers">
           <description>
              Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide
           </description>

           <properties>
               <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
               <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/databaseName?useSSL=false&amp;serverTimezone=UTC&amp;verifyServerCertifate=false&amp;allowPublicKeyRetrieval=true" />
               <property name="javax.persistence.jdbc.user" value="root" />
               <property name="javax.persistence.jdbc.password" value="passwd" />
    <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/>
               <property name="hibernate.show_sql" value="true" />
               <property name="hibernate.format_sql" value="true"/>
               <property name="hibernate.hbm2ddl.auto" value="create" />
           </properties>

       </persistence-unit>

    </persistence>
  2. 创建实体Java类

    import java.util.Date;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;

    import org.hibernate.annotations.GenericGenerator;
    import org.hibernate.envers.Audited;

    @Entity
    @Table( name = "EVENTS" )
    @Audited  // <--- this tell Envers to audit (track changes to) this entity
    public class Event {
       private Long id;

       private String title;
       private Date date;

    public Event() {
    // this form used by Hibernate
    }

    public Event(String title, Date date) {
    // for application use, to create new events
    this.title = title;
    this.date = date;
    }

    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment")
       public Long getId() {
    return id;
      }

       private void setId(Long id) {
    this.id = id;
      }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "EVENT_DATE")
       public Date getDate() {
    return date;
      }

       public void setDate(Date date) {
    this.date = date;   }​    public String getTitle() { return title;   }​    public void setTitle(String title) { this.title = title;   }​ @Override public int hashCode() { int result = title.hashCode(); result = 31 * result + date.hashCode(); return result; }}
  3. 向META-INF/persistence.xml文件中添加映射信息

    <class>类路径.Event</class>
  4. JUnit测试测试程序

    import java.util.Date;
    import java.util.List;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;

    import junit.framework.TestCase;

    import org.hibernate.envers.AuditReader;
    import org.hibernate.envers.AuditReaderFactory;

    /**
    * Illustrates the set up and use of Envers.
    * <p>
    * This example is different from the others in that we really need to save multiple revisions to the entity in
    * order to get a good look at Envers in action.
    *
    * @author Steve Ebersole
    */
    public class EnversIllustrationTest extends TestCase {
    private EntityManagerFactory entityManagerFactory;

    @Override
    protected void setUp() throws Exception {
    // like discussed with regards to SessionFactory, an EntityManagerFactory is set up once for an application
    // IMPORTANT: notice how the name here matches the name we gave the persistence-unit in persistence.xml!
    entityManagerFactory = Persistence.createEntityManagerFactory( "org.hibernate.tutorial.envers" );
    }

    @Override
    protected void tearDown() throws Exception {
    entityManagerFactory.close();
    }

    public void testBasicUsage() {
    // create a couple of events
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    entityManager.persist( new Event( "Our very first event!", new Date() ) );
    entityManager.persist( new Event( "A follow up event", new Date() ) );
    entityManager.getTransaction().commit();
    entityManager.close();

    // now lets pull events from the database and list them
    entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
           List<Event> result = entityManager.createQuery( "from Event", Event.class ).getResultList(); for ( Event event : result ) { System.out.println( "Event (" + event.getDate() + ") : " + event.getTitle() ); }        entityManager.getTransaction().commit();        entityManager.close();​ // so far the code is the same as we have seen in previous tutorials. Now lets leverage Envers...​ // first lets create some revisions entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); Event myEvent = entityManager.find( Event.class, 2L ); // we are using the increment generator, so we know 2 is a valid id myEvent.setDate( new Date() ); myEvent.setTitle( myEvent.getTitle() + " (rescheduled)" );        entityManager.getTransaction().commit();        entityManager.close();​ // and then use an AuditReader to look back through history entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); myEvent = entityManager.find( Event.class, 2L ); assertEquals( "A follow up event (rescheduled)", myEvent.getTitle() ); AuditReader reader = AuditReaderFactory.get( entityManager ); Event firstRevision = reader.find( Event.class, 2L, 1 ); assertFalse( firstRevision.getTitle().equals( myEvent.getTitle() ) ); assertFalse( firstRevision.getDate().equals( myEvent.getDate() ) ); Event secondRevision = reader.find( Event.class, 2L, 2 ); assertTrue( secondRevision.getTitle().equals( myEvent.getTitle() ) ); assertTrue( secondRevision.getDate().equals( myEvent.getDate() ) ); entityManager.getTransaction().commit();        entityManager.close(); }}
  5. 运行测试

Hibernate 5 入门指南-基于Envers的更多相关文章

  1. Hibernate 5 入门指南-基于映射文件

    由于Hibernate 4版本混乱,Hibernate 3有些过时,Hibernate 5的开发文档尚不完善,所以构建一份简单的Hibernate 5的入门指南 注:案例参考Hibernate 官方参 ...

  2. Hibernate 5 入门指南-基于JPA

    首先创建\META-INF\persistence.xml配置文件并做简单的配置 <persistence xmlns="http://java.sun.com/xml/ns/pers ...

  3. Hibernate 5 入门指南-基于类注解

    首先创建hibernate.cfg.xml配置文件并做简单的配置 <hibernate-configuration>    <session-factory>        & ...

  4. 张高兴的 .NET IoT 入门指南:(八)基于 GPS 的 NTP 时间同步服务器

    时间究竟是什么?这既可以是一个哲学问题,也可以是一个物理问题.古人对太阳进行观测,利用太阳的投影发明了日晷,定义了最初的时间.随着科技的发展,天文观测的精度也越来越准确,人们发现地球的自转并不是完全一 ...

  5. Vue.js 入门指南之“前传”(含sublime text 3 配置)

    题记:关注Vue.js 很久了,但就是没有动手写过一行代码,今天准备入手,却发现自己比菜鸟还菜,于是四方寻找大牛指点,才终于找到了入门的“入门”,就算是“入门指南”的“前传”吧.此文献给跟我一样“白痴 ...

  6. 【翻译】Fluent NHibernate介绍和入门指南

    英文原文地址:https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started 翻译原文地址:http://www.cnblogs ...

  7. Flume NG Getting Started(Flume NG 新手入门指南)

    Flume NG Getting Started(Flume NG 新手入门指南)翻译 新手入门 Flume NG是什么? 有什么改变? 获得Flume NG 从源码构建 配置 flume-ng全局选 ...

  8. ReactJS入门指南

    ReactJS入门指南 本文旨在介绍ReactJS的基本知识,并一步步详细介绍React的基本概念和使用方法等,以及相应的Demo.本文在很大程度上参考了React官方文档和官方指南.如果你英语还不错 ...

  9. Webpack 入门指南 - 1.安装

    Webpack 是目前流行的打包工具,如何安装它呢? 1. 安装 Node Js 首先,Webpack 是基于 NodeJs 的工具,你必须首先安装 NodeJs. NodeJs 仅仅只需要在你的系统 ...

随机推荐

  1. Linux命令-设置免密码登录

    设置免密码登陆:[root@Redis01 test]# cd /install/[root@Redis01 install]# rm -rf test/[root@Redis01 install]# ...

  2. 第一册:lesson sixty five.

    原文: Not a baby. A:What are you going to do this evening Jill? B:I'm going to meet some friends, dad. ...

  3. JQuery官方学习资料(译):$( document ).ready()

         一个页面直到document是”ready“才能被安全的操作,Jquery为你检查这种状态.代码包含在$( document ).ready()的内部将会仅仅运行一次在页面Document ...

  4. Java基础IO流(五)RandomAccessFile

    RandomAccessFile java提供的对文件内容的访问,既可以读文件也可以写文件.RandomAccessFile支持随机访问文件,可以访问文件的任意位置 (1)java文件模型:    在 ...

  5. 汇编语言--微机CPU的指令系统(五)(比较运算指令)

    (7)比较运算指令 在程序中,我们要时常根据某个变量或表达式的取值去执行不同指令,从而使程序表现出有不同的功能.为了配合这样的操作,在CPU的指令系统中提供了各种不同的比较指令.通过这些比较指令的执行 ...

  6. js 取数组中某个对象的集合

    var arr = [ {a:1,b:2,c:3}, {a:4,b:5,c:6}, {a:7,b:8,c:9} ]; arr1=[]; arr.forEach(function(v){ arr1.pu ...

  7. BZOJ2946 [Poi2000]公共串(后缀自动机)

    Description          给出几个由小写字母构成的单词,求它们最长的公共子串的长度. 任务: l        读入单词 l        计算最长公共子串的长度 l        输 ...

  8. 获取请求的ip工具类

    package com.example.util; import javax.servlet.http.HttpServletRequest; /** * get remote msg * 获取访问的 ...

  9. Python入门基础之变量和数据类型

    在Python中,能够直接处理的数据类型有以下几种: 一.整数 Python可以处理任意大小的整数,当然包括负整数,在Python程序中,整数的表示方法和数学上的写法一模一样,例如:1,100,-80 ...

  10. Windows 不能在本地计算机启动 OracleDBConsoleorcl的问题解决方法

    解决步骤如下: 1.开始->运行cmd 2.执行 emctl start dbconsole 输入:C:\Documents and Settings\xcl>emctl start db ...