SlideShare a Scribd company logo
1 of 24
Easy Entity Auditing
With Hibernate Envers




    Romain Linsolas
    Java & Web Developer
      Société Générale
      @romaintaz
Romain Linsolas
 Who am I?
 ■ Java & Web developer;
 ■ Technical architect, Software Factory gardener;
 ■ @ Société Générale (french bank)




   http://linsolas.free.fr/wordpress
   @romaintaz
   https://github.com/linsolas
                                                     3
(1) What is Hibernate Envers?
Definition
 Hibernate Envers
   Hibernate module to enable easy auditing of persistent classes!

  Audit = keep a revision of your entity after every "event" (insert,
  update, delete)

   Available since 2009…

         http://www.jboss.org/envers
         http://docs.jboss.org/envers/docs/index.html
         http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html/ch15.html
(2) Activation
Add the Envers library in classpath
 <!-- Requires:
     * Hibernate 3+
     * Hibernate annotations -->
 <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-envers</artifactId>
   <version>4.1.8.Final</version>
 </dependency>




                                               7
(3) Start the audit
Audit a simple entity class
 @Entity
 @Audited
 public class Person {
     @Id @GeneratedValue
     private int id;


     private String name;
     private String surname;


     @ManyToOne
     private Address address;


     // getters, setters, constructors, equals and hashCode…
 }
                                                               9
Some useful Envers @nnotations
 @Audited
 @AuditTable(“T_PERSON_AUDIT”)
 public class Person {


     @NotAudited
     private String comments;


     @AuditJoinTable(name=“T_PERSON_ADDRESS_AUDIT”,
        inverseJoinColumns=@JoinColumn(name=“ADDRESS_ID”))
     public List<Address> address;


 }




                                                             10
What about the database?

     Table T_PERSON
     Id        Name    Surname           Comments



      Table T_PERSON_AUD                                              0     Add
      Id       REV         Name         Surname     REVTYPE           1     Mod
                                                                      2     Del




                                  Table REVINFO
                                  REV      REVTSTMP     (additional info)
Additional information in revisions
 @Entity
 @RevisionEntity(UsernameRevisionListener.class)
 public class MyEntityRevision extends DefaultRevisionEntity {
     private String username;   // + getter / setter
 }




 public class UsernameRevisionListener implements RevisionListener {
     @Override
     public void newRevision(Object revisionEntity) {
         ((MyEntityRevision) revisionEntity).setUsername(getCurrentUsername());
     }
 }
                                                                                  12
Tracking modified fields
  <property name="org.hibernate.envers.global_with_modified_flag" value="true"/>


 Or


      @Audited(withModifiedFlag = true)
      private String myField;



      Table T_PERSON_AUD
      Id          REV      Name      Name_MOD   Surname   Surname_MOD REVTYPE




           Still an experimental feature…
(4) Query audit information
AuditReader
 // Get all the revisions of my current object
 int personId = somePerson.getId();
 AuditReader auditReader = AuditReaderFactory.get(entityManager);
 List<Number> allRevisions = auditReader.getRevisions(Person.class, personId);


 for (Number n: allRevisions) {
     Person p = auditReader.find(Person.class, personId, n);
     System.out.printf("t[Rev #%1$s] > %2$sn", n, p);
 }


     [Rev #1] > Person { id=10, name='Romain', surname='', comments=''}
     [Rev #3] > Person { id=10, name='Romain', surname='Linsolas', comments=''}
     [Rev #4] > null


                                                                                  15
AuditQuery - 1
 AuditQuery query1 = auditReader.createQuery()
      .forEntitiesAtRevision(Person.class, 42);
 List<Person> persons = query1.getResultList();



    Person { id=11, name='Chuck', surname='Norris', comments=''}
    Person { id=10, name='Romain', surname='Linsolas', comments=''}




                                                                      16
AuditQuery - 2
 AuditQuery query2 = auditReader.createQuery()
          .forRevisionsOfEntity(Person.class, false, true);
 List<Object[]> revisions = query2.getResultList();




 Person                                     EntityRevision                                       REVTYPE
 { id=10, name='Romain', surname='',        {id=1, timestamp=1352936106653, username='Devoxx'}   ADD
 comments='' }
 { id=11, name='Chuck', surname='Norris',   {id=2, timestamp=1352936106669, username='Devoxx'}   ADD
 comments='' }
 { id=10, name='Romain',                    {id=3, timestamp=1352936106687, username='Devoxx'}   MOD
 surname='Linsolas', comments='' }
 { id=10, name='null', surname='',          {id=4, timestamp=1352936106734, username='Devoxx'}   DEL
 comments='' }




                                                                                                           17
AuditQuery - 3

 List<Person> persons = auditReader.createQuery()
           .forEntitiesAtRevision(Person.class, 42)
           .addOrder(AuditEntity.property(“surname”).desc())
           .add(AuditEntity.relatedId(“address”).eq(theAddressId))
           .setFirstResult(4)
           .setMaxResults(2)
           .getResultList();




                                                                     18
AuditQuery - 4

 AuditQuery query = auditReader().createQuery()
      .forEntitiesAtRevision(Person.class, 42)
      .add(AuditEntity.property("surname").hasChanged())
      .add(AuditEntity.property("name").hasNotChanged());
https://github.com/linsolas/devoxx-envers
To summarize…
  Pros                              Cons




 Really easy to use!              Require Hibernate
 Configurable                     Not compatible with Hibernate XML
 Ready-to-use audit query tool     configuration (cf. HHH-3887)
 Fully integrated in Hibernate
 No similar project (?)
Q&A
(5) Annexes
Register Envers Listener
 <!-- Needed in persistence.xml or Hibernate configuration if you use older versions of Envers (3.x) -->


 <property name="hibernate.ejb.event.post-insert"
     value="org.hibernate.ejb.event.EJB3PostInsertEventListener,org.hibernate.envers.event.AuditEventListener" />
 <property name="hibernate.ejb.event.post-update"
     value="org.hibernate.ejb.event.EJB3PostUpdateEventListener,org.hibernate.envers.event.AuditEventListener" />
 <property name="hibernate.ejb.event.post-delete"
     value="org.hibernate.ejb.event.EJB3PostDeleteEventListener,org.hibernate.envers.event.AuditEventListener" />


 <property name="hibernate.ejb.event.pre-collection-update"
     value="org.hibernate.envers.event.AuditEventListener" />
 <property name="hibernate.ejb.event.pre-collection-remove"
     value="org.hibernate.envers.event.AuditEventListener" />
 <property name="hibernate.ejb.event.post-collection-recreate"
     value="org.hibernate.envers.event.AuditEventListener" />




                                                                                                                    24

More Related Content

What's hot

4. 대용량 아키텍쳐 설계 패턴
4. 대용량 아키텍쳐 설계 패턴4. 대용량 아키텍쳐 설계 패턴
4. 대용량 아키텍쳐 설계 패턴Terry Cho
 
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard LibraryDongMin Choi
 
JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetHDR1001
 
Cloud Native Java GraalVM 이상과 현실
Cloud Native Java GraalVM 이상과 현실Cloud Native Java GraalVM 이상과 현실
Cloud Native Java GraalVM 이상과 현실Taewan Kim
 
AWS로 게임 기반 다지기 - 김병수, 박진성 :: AWS Game Master 온라인 세미나 #3
AWS로 게임 기반 다지기 - 김병수, 박진성 :: AWS Game Master 온라인 세미나 #3 AWS로 게임 기반 다지기 - 김병수, 박진성 :: AWS Game Master 온라인 세미나 #3
AWS로 게임 기반 다지기 - 김병수, 박진성 :: AWS Game Master 온라인 세미나 #3 Amazon Web Services Korea
 
mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교Woo Yeong Choi
 
CamundaCon 2018: Using Zeebe with Spring Boot and Apache Camel (Holisticon)
CamundaCon 2018: Using Zeebe with Spring Boot and Apache Camel (Holisticon)CamundaCon 2018: Using Zeebe with Spring Boot and Apache Camel (Holisticon)
CamundaCon 2018: Using Zeebe with Spring Boot and Apache Camel (Holisticon)camunda services GmbH
 
Introduction to react
Introduction to reactIntroduction to react
Introduction to reactkiranabburi
 
Decomposing Applications for Scalability and Deployability (April 2012)
Decomposing Applications for Scalability and Deployability (April 2012)Decomposing Applications for Scalability and Deployability (April 2012)
Decomposing Applications for Scalability and Deployability (April 2012)Chris Richardson
 
웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우IMQA
 
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기현철 조
 
심예람, <프로젝트DH> AI 내비게이션 시스템, NDC2018
심예람, <프로젝트DH> AI 내비게이션 시스템, NDC2018심예람, <프로젝트DH> AI 내비게이션 시스템, NDC2018
심예람, <프로젝트DH> AI 내비게이션 시스템, NDC2018devCAT Studio, NEXON
 
Developing event-driven microservices with event sourcing and CQRS (phillyete)
Developing event-driven microservices with event sourcing and CQRS (phillyete)Developing event-driven microservices with event sourcing and CQRS (phillyete)
Developing event-driven microservices with event sourcing and CQRS (phillyete)Chris Richardson
 
코드 리뷰의 또 다른 접근 방법: Pull Requests vs. Stacked Changes
코드 리뷰의 또 다른 접근 방법: Pull Requests vs. Stacked Changes코드 리뷰의 또 다른 접근 방법: Pull Requests vs. Stacked Changes
코드 리뷰의 또 다른 접근 방법: Pull Requests vs. Stacked ChangesJiyeon Seo
 
On to code review lessons learned at microsoft
On to code review lessons learned at microsoftOn to code review lessons learned at microsoft
On to code review lessons learned at microsoftMichaela Greiler
 
Packer, Terraform, Vault를 이용해 만드는 
재현 가능한 게임 인프라
Packer, Terraform, Vault를 이용해 만드는 
재현 가능한 게임 인프라Packer, Terraform, Vault를 이용해 만드는 
재현 가능한 게임 인프라
Packer, Terraform, Vault를 이용해 만드는 
재현 가능한 게임 인프라MinKyu Kim
 

What's hot (20)

4. 대용량 아키텍쳐 설계 패턴
4. 대용량 아키텍쳐 설계 패턴4. 대용량 아키텍쳐 설계 패턴
4. 대용량 아키텍쳐 설계 패턴
 
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
[C++ Korea 2nd Seminar] Ranges for The Cpp Standard Library
 
JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat Sheet
 
Cloud Native Java GraalVM 이상과 현실
Cloud Native Java GraalVM 이상과 현실Cloud Native Java GraalVM 이상과 현실
Cloud Native Java GraalVM 이상과 현실
 
Clean code
Clean codeClean code
Clean code
 
Microservices with Minimal APi and .NET 6
Microservices with Minimal APi and .NET 6Microservices with Minimal APi and .NET 6
Microservices with Minimal APi and .NET 6
 
AWS로 게임 기반 다지기 - 김병수, 박진성 :: AWS Game Master 온라인 세미나 #3
AWS로 게임 기반 다지기 - 김병수, 박진성 :: AWS Game Master 온라인 세미나 #3 AWS로 게임 기반 다지기 - 김병수, 박진성 :: AWS Game Master 온라인 세미나 #3
AWS로 게임 기반 다지기 - 김병수, 박진성 :: AWS Game Master 온라인 세미나 #3
 
mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교
 
Protege tutorial
Protege tutorialProtege tutorial
Protege tutorial
 
CamundaCon 2018: Using Zeebe with Spring Boot and Apache Camel (Holisticon)
CamundaCon 2018: Using Zeebe with Spring Boot and Apache Camel (Holisticon)CamundaCon 2018: Using Zeebe with Spring Boot and Apache Camel (Holisticon)
CamundaCon 2018: Using Zeebe with Spring Boot and Apache Camel (Holisticon)
 
Introduction to react
Introduction to reactIntroduction to react
Introduction to react
 
Decomposing Applications for Scalability and Deployability (April 2012)
Decomposing Applications for Scalability and Deployability (April 2012)Decomposing Applications for Scalability and Deployability (April 2012)
Decomposing Applications for Scalability and Deployability (April 2012)
 
웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우
 
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
 
심예람, <프로젝트DH> AI 내비게이션 시스템, NDC2018
심예람, <프로젝트DH> AI 내비게이션 시스템, NDC2018심예람, <프로젝트DH> AI 내비게이션 시스템, NDC2018
심예람, <프로젝트DH> AI 내비게이션 시스템, NDC2018
 
JVM Under The Hood WDI.pdf
JVM Under The Hood WDI.pdfJVM Under The Hood WDI.pdf
JVM Under The Hood WDI.pdf
 
Developing event-driven microservices with event sourcing and CQRS (phillyete)
Developing event-driven microservices with event sourcing and CQRS (phillyete)Developing event-driven microservices with event sourcing and CQRS (phillyete)
Developing event-driven microservices with event sourcing and CQRS (phillyete)
 
코드 리뷰의 또 다른 접근 방법: Pull Requests vs. Stacked Changes
코드 리뷰의 또 다른 접근 방법: Pull Requests vs. Stacked Changes코드 리뷰의 또 다른 접근 방법: Pull Requests vs. Stacked Changes
코드 리뷰의 또 다른 접근 방법: Pull Requests vs. Stacked Changes
 
On to code review lessons learned at microsoft
On to code review lessons learned at microsoftOn to code review lessons learned at microsoft
On to code review lessons learned at microsoft
 
Packer, Terraform, Vault를 이용해 만드는 
재현 가능한 게임 인프라
Packer, Terraform, Vault를 이용해 만드는 
재현 가능한 게임 인프라Packer, Terraform, Vault를 이용해 만드는 
재현 가능한 게임 인프라
Packer, Terraform, Vault를 이용해 만드는 
재현 가능한 게임 인프라
 

Similar to Devoxx 2012 hibernate envers

Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeMacoscope
 
How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF Luc Bors
 
Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughMahfuz Islam Bhuiyan
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Easy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTEasy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTDavid Chandler
 
APPlause - DemoCamp Munich
APPlause - DemoCamp MunichAPPlause - DemoCamp Munich
APPlause - DemoCamp MunichPeter Friese
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfARORACOCKERY2111
 
Connect.js - Exploring React.Native
Connect.js - Exploring React.NativeConnect.js - Exploring React.Native
Connect.js - Exploring React.Nativejoshcjensen
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Michelangelo van Dam
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperGiordano Scalzo
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web ArtisansRaf Kewl
 
Paying off technical debt with PHPSpec
Paying off technical debt with PHPSpecPaying off technical debt with PHPSpec
Paying off technical debt with PHPSpecLewis Wright
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Anton Arhipov
 

Similar to Devoxx 2012 hibernate envers (20)

Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
How te bring common UI patterns to ADF
How te bring common UI patterns to ADFHow te bring common UI patterns to ADF
How te bring common UI patterns to ADF
 
How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF
 
Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner Walkthrough
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Easy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTEasy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWT
 
APPlause - DemoCamp Munich
APPlause - DemoCamp MunichAPPlause - DemoCamp Munich
APPlause - DemoCamp Munich
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Connect.js - Exploring React.Native
Connect.js - Exploring React.NativeConnect.js - Exploring React.Native
Connect.js - Exploring React.Native
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapper
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web Artisans
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Paying off technical debt with PHPSpec
Paying off technical debt with PHPSpecPaying off technical debt with PHPSpec
Paying off technical debt with PHPSpec
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 

More from Romain Linsolas

Devoxx France 2015 - Développement web en 2015
Devoxx France 2015 - Développement web en 2015Devoxx France 2015 - Développement web en 2015
Devoxx France 2015 - Développement web en 2015Romain Linsolas
 
Devoxx France 2015 - Se préparer à l'arrivée d'Angular 2
Devoxx France 2015 - Se préparer à l'arrivée d'Angular 2Devoxx France 2015 - Se préparer à l'arrivée d'Angular 2
Devoxx France 2015 - Se préparer à l'arrivée d'Angular 2Romain Linsolas
 
Devoxx 2014 - JavaScript tooling - Don't be naked in front of JavaScript
Devoxx 2014 - JavaScript tooling - Don't be naked in front of JavaScriptDevoxx 2014 - JavaScript tooling - Don't be naked in front of JavaScript
Devoxx 2014 - JavaScript tooling - Don't be naked in front of JavaScriptRomain Linsolas
 
Devoxx france 2014 - Création d'un web component avec Google Polymer
Devoxx france 2014 - Création d'un web component avec Google PolymerDevoxx france 2014 - Création d'un web component avec Google Polymer
Devoxx france 2014 - Création d'un web component avec Google PolymerRomain Linsolas
 
Devoxx 2013 JavaScript Software Factory
Devoxx 2013 JavaScript Software FactoryDevoxx 2013 JavaScript Software Factory
Devoxx 2013 JavaScript Software FactoryRomain Linsolas
 
Softshake 2013 - Du JavaScript propre ? Challenge Accepted!
Softshake 2013 - Du JavaScript propre ? Challenge Accepted!Softshake 2013 - Du JavaScript propre ? Challenge Accepted!
Softshake 2013 - Du JavaScript propre ? Challenge Accepted!Romain Linsolas
 
JavaScript Devoxx France 2013
JavaScript Devoxx France 2013JavaScript Devoxx France 2013
JavaScript Devoxx France 2013Romain Linsolas
 
Devoxx java script-1280-720
Devoxx java script-1280-720Devoxx java script-1280-720
Devoxx java script-1280-720Romain Linsolas
 

More from Romain Linsolas (9)

Devoxx France 2015 - Développement web en 2015
Devoxx France 2015 - Développement web en 2015Devoxx France 2015 - Développement web en 2015
Devoxx France 2015 - Développement web en 2015
 
Devoxx France 2015 - Se préparer à l'arrivée d'Angular 2
Devoxx France 2015 - Se préparer à l'arrivée d'Angular 2Devoxx France 2015 - Se préparer à l'arrivée d'Angular 2
Devoxx France 2015 - Se préparer à l'arrivée d'Angular 2
 
Devoxx 2014 - JavaScript tooling - Don't be naked in front of JavaScript
Devoxx 2014 - JavaScript tooling - Don't be naked in front of JavaScriptDevoxx 2014 - JavaScript tooling - Don't be naked in front of JavaScript
Devoxx 2014 - JavaScript tooling - Don't be naked in front of JavaScript
 
Devoxx france 2014 - Création d'un web component avec Google Polymer
Devoxx france 2014 - Création d'un web component avec Google PolymerDevoxx france 2014 - Création d'un web component avec Google Polymer
Devoxx france 2014 - Création d'un web component avec Google Polymer
 
Devoxx 2013 JavaScript Software Factory
Devoxx 2013 JavaScript Software FactoryDevoxx 2013 JavaScript Software Factory
Devoxx 2013 JavaScript Software Factory
 
Softshake 2013 - Du JavaScript propre ? Challenge Accepted!
Softshake 2013 - Du JavaScript propre ? Challenge Accepted!Softshake 2013 - Du JavaScript propre ? Challenge Accepted!
Softshake 2013 - Du JavaScript propre ? Challenge Accepted!
 
JavaScript Devoxx France 2013
JavaScript Devoxx France 2013JavaScript Devoxx France 2013
JavaScript Devoxx France 2013
 
Devoxx test ng
Devoxx test ngDevoxx test ng
Devoxx test ng
 
Devoxx java script-1280-720
Devoxx java script-1280-720Devoxx java script-1280-720
Devoxx java script-1280-720
 

Recently uploaded

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 

Recently uploaded (20)

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Devoxx 2012 hibernate envers

  • 1.
  • 2. Easy Entity Auditing With Hibernate Envers Romain Linsolas Java & Web Developer Société Générale @romaintaz
  • 3. Romain Linsolas Who am I? ■ Java & Web developer; ■ Technical architect, Software Factory gardener; ■ @ Société Générale (french bank) http://linsolas.free.fr/wordpress @romaintaz https://github.com/linsolas 3
  • 4. (1) What is Hibernate Envers?
  • 5. Definition Hibernate Envers Hibernate module to enable easy auditing of persistent classes! Audit = keep a revision of your entity after every "event" (insert, update, delete) Available since 2009… http://www.jboss.org/envers http://docs.jboss.org/envers/docs/index.html http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html/ch15.html
  • 7. Add the Envers library in classpath <!-- Requires: * Hibernate 3+ * Hibernate annotations --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> <version>4.1.8.Final</version> </dependency> 7
  • 9. Audit a simple entity class @Entity @Audited public class Person { @Id @GeneratedValue private int id; private String name; private String surname; @ManyToOne private Address address; // getters, setters, constructors, equals and hashCode… } 9
  • 10. Some useful Envers @nnotations @Audited @AuditTable(“T_PERSON_AUDIT”) public class Person { @NotAudited private String comments; @AuditJoinTable(name=“T_PERSON_ADDRESS_AUDIT”, inverseJoinColumns=@JoinColumn(name=“ADDRESS_ID”)) public List<Address> address; } 10
  • 11. What about the database? Table T_PERSON Id Name Surname Comments Table T_PERSON_AUD 0 Add Id REV Name Surname REVTYPE 1 Mod 2 Del Table REVINFO REV REVTSTMP (additional info)
  • 12. Additional information in revisions @Entity @RevisionEntity(UsernameRevisionListener.class) public class MyEntityRevision extends DefaultRevisionEntity { private String username; // + getter / setter } public class UsernameRevisionListener implements RevisionListener { @Override public void newRevision(Object revisionEntity) { ((MyEntityRevision) revisionEntity).setUsername(getCurrentUsername()); } } 12
  • 13. Tracking modified fields <property name="org.hibernate.envers.global_with_modified_flag" value="true"/> Or @Audited(withModifiedFlag = true) private String myField; Table T_PERSON_AUD Id REV Name Name_MOD Surname Surname_MOD REVTYPE Still an experimental feature…
  • 14. (4) Query audit information
  • 15. AuditReader // Get all the revisions of my current object int personId = somePerson.getId(); AuditReader auditReader = AuditReaderFactory.get(entityManager); List<Number> allRevisions = auditReader.getRevisions(Person.class, personId); for (Number n: allRevisions) { Person p = auditReader.find(Person.class, personId, n); System.out.printf("t[Rev #%1$s] > %2$sn", n, p); } [Rev #1] > Person { id=10, name='Romain', surname='', comments=''} [Rev #3] > Person { id=10, name='Romain', surname='Linsolas', comments=''} [Rev #4] > null 15
  • 16. AuditQuery - 1 AuditQuery query1 = auditReader.createQuery() .forEntitiesAtRevision(Person.class, 42); List<Person> persons = query1.getResultList(); Person { id=11, name='Chuck', surname='Norris', comments=''} Person { id=10, name='Romain', surname='Linsolas', comments=''} 16
  • 17. AuditQuery - 2 AuditQuery query2 = auditReader.createQuery() .forRevisionsOfEntity(Person.class, false, true); List<Object[]> revisions = query2.getResultList(); Person EntityRevision REVTYPE { id=10, name='Romain', surname='', {id=1, timestamp=1352936106653, username='Devoxx'} ADD comments='' } { id=11, name='Chuck', surname='Norris', {id=2, timestamp=1352936106669, username='Devoxx'} ADD comments='' } { id=10, name='Romain', {id=3, timestamp=1352936106687, username='Devoxx'} MOD surname='Linsolas', comments='' } { id=10, name='null', surname='', {id=4, timestamp=1352936106734, username='Devoxx'} DEL comments='' } 17
  • 18. AuditQuery - 3 List<Person> persons = auditReader.createQuery() .forEntitiesAtRevision(Person.class, 42) .addOrder(AuditEntity.property(“surname”).desc()) .add(AuditEntity.relatedId(“address”).eq(theAddressId)) .setFirstResult(4) .setMaxResults(2) .getResultList(); 18
  • 19. AuditQuery - 4 AuditQuery query = auditReader().createQuery() .forEntitiesAtRevision(Person.class, 42) .add(AuditEntity.property("surname").hasChanged()) .add(AuditEntity.property("name").hasNotChanged());
  • 21. To summarize… Pros Cons  Really easy to use!  Require Hibernate  Configurable  Not compatible with Hibernate XML  Ready-to-use audit query tool configuration (cf. HHH-3887)  Fully integrated in Hibernate  No similar project (?)
  • 22. Q&A
  • 24. Register Envers Listener <!-- Needed in persistence.xml or Hibernate configuration if you use older versions of Envers (3.x) --> <property name="hibernate.ejb.event.post-insert" value="org.hibernate.ejb.event.EJB3PostInsertEventListener,org.hibernate.envers.event.AuditEventListener" /> <property name="hibernate.ejb.event.post-update" value="org.hibernate.ejb.event.EJB3PostUpdateEventListener,org.hibernate.envers.event.AuditEventListener" /> <property name="hibernate.ejb.event.post-delete" value="org.hibernate.ejb.event.EJB3PostDeleteEventListener,org.hibernate.envers.event.AuditEventListener" /> <property name="hibernate.ejb.event.pre-collection-update" value="org.hibernate.envers.event.AuditEventListener" /> <property name="hibernate.ejb.event.pre-collection-remove" value="org.hibernate.envers.event.AuditEventListener" /> <property name="hibernate.ejb.event.post-collection-recreate" value="org.hibernate.envers.event.AuditEventListener" /> 24