Envers –tracked your Entity Objects

原文地址:http://get2java.wordpress.com/2011/06/27/envers-easy-auditing-for-entity-classes/

HaveyoutrackedyourEntityObjects?Whenithascreated,modifiedanddeletedwithtime.

TryEnversforEasyAuditingofEntityClasses.VerysimpletoaudityourEntityclassesusing@Audited.EnversnowbecomesapartofHibernate3.5.

Listoflibrariesyouneedforthis

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

AddtheAuditEventListenersinyourhibernate.cfg.xml

01

<?xmlversion="1.0"encoding="UTF-8"?>

02

<!DOCTYPEhibernate-configurationPUBLIC

03

"-//Hibernate/HibernateConfigurationDTD3.0//EN"

04

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

05

<hibernate-configuration>

06

<session-factory>

07

<!--Databaseconnectionsettings-->

08

<propertyname="connection.driver_class">com.mysql.jdbc.Driver</property>

09

<propertyname="connection.url">jdbc:mysql://localhost:3306/envers</property>

10

<propertyname="connection.username">root</property>

11

<propertyname="connection.password">welcome123</property>

12

<!--JDBCconnectionpool(usethebuilt-in)-->

13

<propertyname="connection.pool_size">1</property>

14

<!--SQLdialect-->

15

<propertyname="dialect">org.hibernate.dialect.MySQLDialect</property>

16

<!--EnableHibernate'sautomaticsessioncontextmanagement-->

17

<propertyname="current_session_context_class">thread</property>

18

<!--Disablethesecond-levelcache-->

19

<propertyname="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

20

<!--EchoallexecutedSQLtostdout-->

21

<propertyname="show_sql">true</property>

22

<!--Dropandre-createthedatabaseschemaonstartup-->

23

<propertyname="hbm2ddl.auto">update</property>

24

<mapping/>

25

<!--HibernateENVERSListenerConfiguration-->

26

<listenerclass="org.hibernate.envers.event.AuditEventListener"type="post-insert"/>

27

<listenerclass="org.hibernate.envers.event.AuditEventListener"type="post-update"/>

28

<listenerclass="org.hibernate.envers.event.AuditEventListener"type="post-delete"/>

29

<listenerclass="org.hibernate.envers.event.AuditEventListener"type="pre-collection-update"/>

30

<listenerclass="org.hibernate.envers.event.AuditEventListener"type="pre-collection-remove"/>

31

<listenerclass="org.hibernate.envers.event.AuditEventListener"type="post-collection-recreate"/>

32

</session-factory>

33

</hibernate-configuration>

2.EntityClass

YourEntityclassshouldhave@Auditedfortrackingthevaluesinthepersistentclass.

01

packagecom;

02

importjava.io.Serializable;

03

importjavax.persistence.Column;

04

importjavax.persistence.Entity;

05

importjavax.persistence.GeneratedValue;

06

importjavax.persistence.Id;

07

importjavax.persistence.Table;

08

importorg.hibernate.envers.Audited;

09

10

/**

11

*@authorAnand

12

*

13

*/

14

@Entity

15

@Table(name="user")

16

@Audited//----------------Thisismoreimportant!!!!!!!!

17

publicclassUserimplementsSerializable{

18

@Id

19

@GeneratedValue

20

@Column(name="id")

21

privateintid;

22

@Column(name="firstname")

23

privateStringfirstname;

24

@Column(name="lastname")

25

privateStringlastname;

26

@Column(name="email")

27

privateStringemail;

28

/**

29

*@returntheemail

30

*/

31

publicStringgetEmail(){

32

returnemail;

33

}

34

/**

35

*@paramemailtheemailtoset

36

*/

37

publicvoidsetEmail(Stringemail){

38

this.email=email;

39

}

40

/**

41

*@returnthefirstname

42

*/

43

publicStringgetFirstname(){

44

returnfirstname;

45

}

46

/**

47

*@paramfirstnamethefirstnametoset

48

*/

49

publicvoidsetFirstname(Stringfirstname){

50

this.firstname=firstname;

51

}

52

/**

53

*@returntheid

54

*/

55

publicintgetId(){

56

returnid;

57

}

58

/**

59

*@paramidtheidtoset

60

*/

61

publicvoidsetId(intid){

62

this.id=id;

63

}

64

/**

65

*@returnthelastname

66

*/

67

publicStringgetLastname(){

68

returnlastname;

69

}

70

/**

71

*@paramlastnamethelastnametoset

72

*/

73

publicvoidsetLastname(Stringlastname){

74

this.lastname=lastname;

75

}

76

}

3.DBStructureofyourEntityclass

FieldTypeNullKeyDefaultExtra

idint(11)NOPRINULLauto_increment

firstnamevarchar(128)YESNULL

lastnamevarchar(128)YESNULL

emailvarchar(64)YESNULL

4.Insertthedata

NowletsbeginwithInsertthedata

AddthedatatoyourEntityClass

1

Useruser=newUser();

2

user.setFirstname("biju");

3

user.setLastname("cd");

4

user.setEmail("[email protected]");

GettheSessionFactoryandSessiontosavethedataintoDB

01

/**GettingtheSessionFactoryandsession*/

02

//SessionFactorysessionfactory=HibernateUtil.getSessionFactory();

03

SessionFactorysessionfactory=newAnnotationConfiguration().configure().buildSessionFactory();

04

Sessionsess=sessionfactory.getCurrentSession();

05

/**StartingtheTransaction*/

06

Trans)actiontx=sess.beginTransaction();

07

/**SavingPOJO*/

08

sess.save(user);

09

/**Commitingthechanges*/

10

tx.commit();

11

System.out.println("RecordInserted");

12

/**ClosingSession*/

13

sessionfactory.close();

5.NewTablesCreatedforholdingtheRevisionEntries

Table1:user_aud(AuditTable)

Audittablewillhavethedefaultsuffixtobe_audandpresentinthedefaultschemaofthedatabase.

IthasthesamestructureastheEntitytable.Additionallyithasthreecolumnsinitnamely

id

REV

REVINFO

FieldTypeNullKeyDefaultExtra

idint(11)NOPRINULLauto_increment

REVint(11)NOPRINULL

REVTYPEtinyint(11)YES

firstnamevarchar(128)YESNULL

lastnamevarchar(128)YESNULL

emailvarchar(64)YESNULL

Table2:revinfo(commontablefortheEntity)

ThisrevinfotablewillbecommonforalltheEntityclasses.

FieldTypeNullKeyDefaultExtra

REVint(11)NOPRINULLauto_increment

REVTSTMPbigint(20)YES

Thistwotableswillbeautomaticallycreated.

6.EntriesintheAudittableandRevinfotableafterinsert

idREVREVTYPEemailfirstnamelastname

[email protected]

Heretheidcolumnisforeignkeyfortheentityclass“user”,REVwillbeprimarykeyfortheauditedtable.MoreImportantlytheREVTYPEhasthreevaluesinit.

0=Creation

1=Update

2=Delete

Whenevertheinsertiontakesfortheentityclass“user”,itmakesanentryasZeroandkeepsalltheAuditedcolumnsvaluesinit.(0=Creation)

LookintoRevinfotable

REVREVTSTMP

1134343453534434

ItcontainstheRevisionTimestampvalue.

7.UpdatethedataandLookintoAuditTables

1

Useruser=newUser();

2

user.setId(1);//Passestheid=1totheEntityClass

01

/**GettingtheSessionFactoryandsession*/

02

SessionFactorysessionfactory=HibernateUtil.getSessionFactory();

03

Sessionsess=sessionfactory.getCurrentSession();

04

/**StartingtheTransaction*/

05

Transactiontx=sess.beginTransaction();

06

Useru=(User)sess.get(User.class,user.getId());

07

u.setFirstname("biju-append");

08

u.setLastname("cd-append");

09

u.setEmail("[email protected]");

10

sess.saveOrUpdate(u);

11

/**Commitingthechanges*/

12

tx.commit();

13

System.out.println("RecordUpdated");

14

/**ClosingSession*/

15

sessionfactory.close();

LookintotheAuditTable

idREVREVTYPEemailfirstnamelastname

[email protected]

[email protected]

biju-append

cd-append

Note1isforUpdate(REVTYPE)

REVREVTSTMP

1134343453534434

2134343453534434

Whenweupdatethesamerecord,itupdatestheAuditedcolumnsvaluesandupdatetheREVTYPEtobe1.(1=Updation)

8.DeletethedataandLookintoAuditTables

1

Useruser=newUser();

2

user.setId(1);//Passestheid=1totheEntityClasstodelete

01

/**GettingtheSessionFactoryandsession*/

02

SessionFactorysessionfactory=HibernateUtil.getSessionFactory();

03

Sessionsess=sessionfactory.getCurrentSession();

04

/**StartingtheTransaction*/

05

Transactiontx=sess.beginTransaction();

06

Useru=(User)sess.get(User.class,user.getId());

07

sess.delete(u);

08

/**Commitingthechanges*/

09

tx.commit();

10

System.out.println("RecordDeleted");

11

/**ClosingSession*/

12

sessionfactory.close();

LookintotheAuditTable

idREVREVTYPEemailfirstnamelastname

[email protected]

[email protected]

biju-append

cd-append

132NULL

NULL

NULL

Note2isforDelete(REVTYPE)

REVREVTSTMP

1134343453534434

2134343453534434

3134343452343243

WhenthedataisDeleted,therowhasbeendeletedintheEntitytable.ButintheAuditedTable,itupdatesalltheAuditedcolumnstobeNULLandupdatestheREVTYPEtobe2.(2=Delete)

相关推荐