欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Envers –tracked your Entity Objects

程序员文章站 2024-01-09 20:20:58
...
原文地址:http://get2java.wordpress.com/2011/06/27/envers-easy-auditing-for-entity-classes/
Have you tracked your Entity Objects ? When it has created,modified and deleted with time.

Try Envers for Easy Auditing of Entity Classes. Very simple to audit your Entity classes using @Audited. Envers now becomes a part of Hibernate 3.5.

List of libraries you need for this

hibernate3.jar
antlr.jar
commons-collections.jar
dom4j-1.6.1.jar
javassist.jar
jpa-api-2.0-1.jar
jta.jar
mysql-connector-java-5.1.3-rc-bin.jar
slf4j-api-1.6.1.jar
1. hibernate.cfg.xml

Add the Audit Event Listeners in your hibernate.cfg.xml

01
<?xml version="1.0" encoding="UTF-8"?>
02
<!DOCTYPE hibernate-configuration PUBLIC
03
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
04
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
05
<hibernate-configuration>
06
<session-factory>
07
<!-- Database connection settings -->
08
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
09
<property name="connection.url">jdbc:mysql://localhost:3306/envers</property>
10
<property name="connection.username">root</property>
11
<property name="connection.password">welcome123</property>
12
<!-- JDBC connection pool (use the built-in) -->
13
<property name="connection.pool_size">1</property>
14
<!-- SQL dialect -->
15
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
16
<!-- Enable Hibernate's automatic session context management -->
17
<property name="current_session_context_class">thread</property>
18
<!-- Disable the second-level cache -->
19
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
20
<!-- Echo all executed SQL to stdout -->
21
<property name="show_sql">true</property>
22
<!-- Drop and re-create the database schema on startup -->
23
<property name="hbm2ddl.auto">update</property>
24
<mapping/>
25
<!-- Hibernate ENVERS Listener Configuration -->
26
<listener class="org.hibernate.envers.event.AuditEventListener" type="post-insert"/>
27
<listener class="org.hibernate.envers.event.AuditEventListener" type="post-update"/>
28
<listener class="org.hibernate.envers.event.AuditEventListener" type="post-delete"/>
29
<listener class="org.hibernate.envers.event.AuditEventListener" type="pre-collection-update"/>
30
<listener class="org.hibernate.envers.event.AuditEventListener" type="pre-collection-remove"/>
31
<listener class="org.hibernate.envers.event.AuditEventListener" type="post-collection-recreate"/>
32
</session-factory>
33
</hibernate-configuration>

2. Entity Class

Your Entity class should have @Audited for tracking the values in the persistent class.

01
package com;
02
import java.io.Serializable;
03
import javax.persistence.Column;
04
import javax.persistence.Entity;
05
import javax.persistence.GeneratedValue;
06
import javax.persistence.Id;
07
import javax.persistence.Table;
08
import org.hibernate.envers.Audited;
09

10
/**
11
* @author Anand
12
*
13
*/
14
@Entity
15
@Table(name="user")
16
@Audited //---------------- This is more important!!!!!!!!
17
public class User implements Serializable {
18
@Id
19
@GeneratedValue
20
@Column(name="id")
21
private int id;
22
@Column(name="firstname")
23
private String firstname;
24
@Column(name="lastname")
25
private String lastname;
26
@Column(name="email")
27
private String email;
28
/**
29
* @return the email
30
*/
31
public String getEmail() {
32
return email;
33
}
34
/**
35
* @param email the email to set
36
*/
37
public void setEmail(String email) {
38
this.email = email;
39
}
40
/**
41
* @return the firstname
42
*/
43
public String getFirstname() {
44
return firstname;
45
}
46
/**
47
* @param firstname the firstname to set
48
*/
49
public void setFirstname(String firstname) {
50
this.firstname = firstname;
51
}
52
/**
53
* @return the id
54
*/
55
public int getId() {
56
return id;
57
}
58
/**
59
* @param id the id to set
60
*/
61
public void setId(int id) {
62
this.id = id;
63
}
64
/**
65
* @return the lastname
66
*/
67
public String getLastname() {
68
return lastname;
69
}
70
/**
71
* @param lastname the lastname to set
72
*/
73
public void setLastname(String lastname) {
74
this.lastname = lastname;
75
}
76
}
3. DB Structure of your Entity class

Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
firstname varchar(128) YES NULL
lastname varchar(128) YES NULL
email varchar(64) YES NULL
4. Insert the data
Now lets begin with Insert the data
Add the data to your Entity Class

1
User user = new User();
2
user.setFirstname("biju");
3
user.setLastname("cd");
4
user.setEmail("cdbiju@gmail.com");
Get the Session Factory and Session to save the data into DB

01
/** Getting the Session Factory and session */
02
//SessionFactory sessionfactory = HibernateUtil.getSessionFactory();
03
SessionFactory sessionfactory = new AnnotationConfiguration().configure().buildSessionFactory();
04
Session sess = sessionfactory.getCurrentSession();
05
/** Starting the Transaction */
06
Trans)action tx = sess.beginTransaction();
07
/** Saving POJO */
08
sess.save(user);
09
/** Commiting the changes */
10
tx.commit();
11
System.out.println("Record Inserted");
12
/** Closing Session */
13
sessionfactory.close();
5. New Tables Created for holding the Revision Entries

Table 1 : user_aud(Audit Table)

Audit table will have the default suffix to be _aud and present in the default schema of the database.
It has the same structure as the Entity table. Additionally it has three columns in it namely

id
REV
REVINFO
Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
REV int(11) NO PRI NULL
REVTYPE tinyint(11) YES
firstname varchar(128) YES NULL
lastname varchar(128) YES NULL
email varchar(64) YES NULL
Table 2 : revinfo(common table for the Entity)

This revinfo table will be common for all the Entity classes.
Field Type Null Key Default Extra
REV int(11) NO PRI NULL auto_increment
REVTSTMP bigint(20) YES
This two tables will be automatically created.
6. Entries in the Audit table and Revinfo table after insert

id REV REVTYPE email firstname lastname
1 1 0 cdbiju@gmail.com biju cd
Here the id column is foreign key for the entity class “user”, REV will be primary key for the audited table. More Importantly the REVTYPE has three values in it.

0 = Creation

1 = Update

2 = Delete

Whenever the insertion takes for the entity class “user”,  it makes an entry as Zero and keeps all the  Audited columns values in it. (0 = Creation)

Look into Revinfo table

REV REVTSTMP
1 134343453534434
It contains the Revision Timestamp value.

7. Update the data and Look into Audit Tables

1
User user = new User();
2
user.setId(1);   // Passes the id=1 to the Entity Class
01
/** Getting the Session Factory and session */
02
SessionFactory sessionfactory = HibernateUtil.getSessionFactory();
03
Session sess = sessionfactory.getCurrentSession();
04
/** Starting the Transaction */
05
Transaction tx = sess.beginTransaction();
06
User u = (User) sess.get(User.class, user.getId());
07
u.setFirstname("biju-append");
08
u.setLastname("cd-append");
09
u.setEmail("cdbiju-append@gmail.com");
10
sess.saveOrUpdate(u);
11
/** Commiting the changes */
12
tx.commit();
13
System.out.println("Record Updated");
14
/** Closing Session */
15
sessionfactory.close();
Look into the Audit Table

id REV REVTYPE email firstname lastname
1 1 0 cdbiju@gmail.com biju Cd
1 2 1 cdbiju-append@gmail.com
biju-append


cd-append


Note 1 is for Update (REVTYPE)

REV REVTSTMP
1 134343453534434
2 134343453534434
When we update the same record, it updates the Audited columns values and update the REVTYPE to be 1.( 1 = Updation)

8. Delete the data and Look into Audit Tables

1
User user = new User();
2
user.setId(1);   // Passes the id=1 to the Entity Class to delete
01
/** Getting the Session Factory and session */
02
SessionFactory sessionfactory = HibernateUtil.getSessionFactory();
03
Session sess = sessionfactory.getCurrentSession();
04
/** Starting the Transaction */
05
Transaction tx = sess.beginTransaction();
06
User u = (User) sess.get(User.class, user.getId());
07
sess.delete(u);
08
/** Commiting the changes */
09
tx.commit();
10
System.out.println("Record Deleted");
11
/** Closing Session */
12
sessionfactory.close();
Look into the Audit Table

id REV REVTYPE email firstname lastname
1 1 0 cdbiju@gmail.com biju Cd
1 2 1 cdbiju-append@gmail.com
biju-append


cd-append


1 3 2 NULL
NULL
NULL
Note 2 is for Delete (REVTYPE)

REV REVTSTMP
1 134343453534434
2 134343453534434
3 134343452343243
When the data is Deleted, the row has been deleted in the Entity table . But in the Audited Table, it updates all the Audited columns to be NULL and updates the REVTYPE to be 2.(2 = Delete)