Reputation: 923
I am using hibernate version 5.2.12.Final jar.I want to getEntityName in hibernate Envers.I have a Book class annotated with @Audited.
@Audited
@Entity(name="Book")
//hib envers to audit and revision for handle ddl/dml operation.
/*@RevisionEntity // to get revision entity
*/
@Table(name = "Book")
public class Book /*extends DefaultRevisionEntity*/{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String title;
private String author;
public long getId() {
return id;
}
I am trying :
AuditReader reader = AuditReaderFactory.get(HibernateUtil.getSessionFactory().openSession());
String entityName = reader.getEntityName(3, 1,"Book");
System.out.println("Entity Name : " + entityName);
But throwing an exception :
org.hibernate.HibernateException: Envers can't resolve entityName for historic entity. The id, revision and entity is not on envers first level cache.
at org.hibernate.envers.internal.reader.AuditReaderImpl.getEntityName(AuditReaderImpl.java:327)
at com.boraji.tutorial.hibernate.MainApp.main(MainApp.java:119)
Help will appreciate, Thanks.
Upvotes: 0
Views: 2673
Reputation: 21143
In order to get your audit entity name, you should refer to this post which describes how to obtain that if you know your ORM entity name up-front.
In order to obtain the ORM entity name, there are actually several ways you can obtain this. One likely very portable way is to access the Metamodel
for your given entity class and get its name.
Session session = // get your session from somewhere
String name = session.getMetamodel().entity( YourEntityClass.class ).getName();
Another alternative would be to access it from the EntityPersister
interface. Be aware that this won't necessarily be portable across minor releases as this is using an SPI but its an option. You first need to obtain the SessionImplementor
, which the above post illustrates. Once you have the persister, its a simple method call
String name = sessionImplementor.getFactory()
.locateEntityPersister( YourEntityClass.class )
.getEntityName();
Now reading the java-doc for AuditReader#getEntityName()
, the documentation does state that the method should return null
in the event that it cannot determine the entity-name and while the method signature designates it can throw a HibernateException
, there is no documentation clarifying why that exception can be thrown.
That said, that exception is thrown when the supplied object, revision, and identifier have not yet been read and cached by the AuditReader
instance you call #getEntityName()
upon. That means if you open a reader, get the instance, and then use a new AuditReader
instance to get the entity name, you will get this error.
I've added a JIRA HHH-12373 in order to handle addressing the java-doc misunderstanding.
Upvotes: 2