Audit JPA entities eclipselink - java

I need to audit updates, inserts and deletes, i'm using eclipselink as JPA provider. I need to store all modified data.
I tried to use #PrePersist for the merge but i don't know why, it is not called, and it's not possible to pass a object as my data before.
Other problem is that in update transactions i will need to store data as it was before and after the transaction to do a comparison, same in deleting, i need to store data that was deleted.
What is the best way to do this?
#Entity
#EntityListeners(FrotaListener.class)
#Table(name="frota" , schema="sap")
#NamedQuery(name="Frota.findAll", query="SELECT f FROM Frota f")
public class Frota implements Serializable {..}
public class FrotaListener {
#PrePersist
#PreUpdate
#PreRemove
private void beforeAnyOperation(Object object) {
System.out.println("teste");
}
}
try {
em.getTransaction().begin();
em.flush();
em.merge(frota);
em.flush();
em.getTransaction().commit();
} catch (Exception e) {
sqlErrorParse(e);
e.printStackTrace();
}finally {
em.close();
}
and FrotaListener is never called

Related

Hibernate - 1 Class 2 Tables

I have a simple table and I want to store them in another table aswell (create a historic of users). Let's call it Users. I created a table exactly like Users (only different id name) called HISTORY_Users.
So I created the table and now I realize that I have 2 tables for 1 object. So how do I add my object only to the hist table?
I dont want to add them at the same time. I want to add the user to the hist only when he deletes the accounts.
I'm using Hibernate with xml mapping
//when the user deletes the account I call this function and pass the User
private static void addToHist(User User) {
//how do I add only to HIST_Users table??
Database.addToDatabase(user);
}
//Save the object to the database
public static void addToDatabase(Object object) {
SessionFactory factory = HibernateUtil.GetSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
session.save(object);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
Maybe better solution will be use the Hibernate Envers: http://hibernate.org/orm/envers/
You can configure when you want to put it into history: on create, update or delete.
Tables are created automatically, you need to add some annotations only like #Audited etc.

How to update detached entities?

I want to perform multiple updates on an #Entity. But based on some evaulations, I have to execute long running tasks in between. The task itself is based on a property of that entity. Thus, I first have to fetch the entity, merge some content, run the long task, and merge again.
This would span the database transaction, which is probably not correct:
#Transactional
public void update(DTO dto) {
entity = findOne(dto.id);
updateEntityFieldsFromDTO(entity, dto);
if (entity.hasTaskCondition) {
result = runLongTask(entity.property); //spanning the tx
mergeResultIntoEntity(entity, result);
}
}
Problem: the runLongTask() will block the transaction and keep the database connection open maybe for a long time, without interaction on the db.
Thus I thought creating single #Transactional methods, and running the task ouside of those tx:
//wrapper method without a transaction
public void updateFacade(DTO dto) {
entity = service.update(dto.id);
if (entity.hasTaskCondition) {
//running outside the transaction
result = runLongTask(entity.property);
service.mergeResultIntoEntity(entity.id, result);
}
}
Then my transactional methods would be as follows:
#Transactional
public Entity update(DTO dto) {
//first select the entity
entity = findOne(dto.id);
//then merge the content
updateEntityFieldsFromDTO(entity, dto);
return entity;
}
#Transactional
public Entity mergeResultIntoEntity(id, result) {
//again select the entity
entity = findOne(dto.id);
//now merge result into entity within tx
return entity;
}
Question: is it correct to always pass the entity.id to the #Transactional methods, and then fetch the object from db again inside those tx methods?
I think I cannot pass the entity directly into the #Transactional methods from updateFacade, as the entity is detached. Correct?

Jackson mapping a relationship

I'm using Jersey and am expecitng a POST as an entity. However thst POST will also contain the UUID for one of its relationships:
Jersey Resource:
#POST
public WorkstationEntity save (WorkstationEntity workstationEntity) {
//WorkflowProcessEntity workflowProcessEntity = workflowProcessService.findByUUID();
workstationService.save(workstationEntity);
return workstationEntity;
}
How can I adjust the following mapping so it'll recognize the relationship and save correctly? Currently the workflow_process_id is NULL when it's saved and I have to query for the entity manually.
The JSON being posted is... {name: Workstation 1; workflow_process_id: 1}
private WorkflowProcessEntity workflowProcess;
#ManyToOne
#JoinColumn(name = "workflow_process_id", referencedColumnName = "id")
public WorkflowProcessEntity getWorkflowProcess() {
return workflowProcess;
}
public void setWorkflowProcess(WorkflowProcessEntity workflowProcess) {
this.workflowProcess = workflowProcess;
}
workstationService
#Transactional
public void save(WorkstationEntity workstationEntity) {
workstationRepository.save(workstationEntity);
}
Can you show code for workstationService? are you using Hibernatr or simple jdbc or any other orm tool?
I think inside workstationService.save(workstationEntity); you will need to attach workstationEntity to session (in case of Hibernate Hibernate Session). and then save it..
If I understand the problem it is that the returning json has a null id for the attached WorkstationProcessEntity id field. This is most likely a problem when you are trying to persist / merge the entity the transaction is not being committed before returning the detached entity. If you are using a persist make sure that you commit the transaction otherwise the id's will be null. Otherwise if you are using a merge this will commonly fix the problem.
protected T persist(T obj) {
EntityManager em = ThreadLocalPersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
if (! tx.isActive()) {
tx.begin();
}
em.persist(obj);
} finally {
if (!tx.getRollbackOnly()) {
tx.commit();
}
}
return obj;
}
The other likely cause is that your fetch is not set to eager so the datastore will only fetch the entity when it is accessed and by the time you are returning from the post the child entity is not attached. This is the most likely cause for your problem. What you should try is to access the workstation entitites getWorkflowProcess before closing the entity manager. Otherwise the attached entities will be null. Or add the FetchType.Eager annotation to fetch the child entities from the database when the parent is accessed.

javax.jdo.JDODetachedFieldAccessException when I ask for a List<T> using JPA and Datastore

im having javax.jdo.JDODetachedFieldAccessException when i want to, after retrieve all of my Entites as a List in my DAO implementation, ask for one atrribute object from my Entity.
public List<T> findAll() {
this.entityManager = SingletonEntityManagerFactory.get().createEntityManager();
EntityTransaction tx = this.entityManager.getTransaction();
try {
tx.begin();
return this.entityManager.createQuery(
"select f from " + clazz.getName() + " as f").getResultList();
}finally {
tx.commit();
if (tx.isActive()) {
tx.rollback();
}
this.entityManager.close();
}
}
for instance, supposing T has a property of class A that is already an Entity persisted, i can't get A after having List
But i don't have this problem if I only look for a single Entity by Id. I obtain my entity and I can ask without problems for its attribute objects already persisted
public T getById(final Key id) {
return getEntityManager().find(clazz, id);
}
now i can do
A a= t.getA();
How can I write my implementation of findAll() avoiding this error? maybe another Component instead of EntityManager? How can i make it generic, and not having to implement specific code for specific type of entities?
What you do there doesn't make sure the field is loaded before leaving that method, so either access it, or make sure it is fetched by default.

Working with hibernate/DAO problems

Hello everyone here is my DAO class :
public class UsersDAO extends HibernateDaoSupport {
private static final Log log = LogFactory.getLog(UsersDAO.class);
protected void initDao() {
//do nothing
}
public void save(User transientInstance) {
log.debug("saving Users instance");
try {
getHibernateTemplate().saveOrUpdate(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void update(User transientInstance) {
log.debug("updating User instance");
try {
getHibernateTemplate().update(transientInstance);
log.debug("update successful");
} catch (RuntimeException re) {
log.error("update failed", re);
throw re;
}
}
public void delete(User persistentInstance) {
log.debug("deleting Users instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public User findById( java.lang.Integer id) {
log.debug("getting Users instance with id: " + id);
try {
User instance = (User) getHibernateTemplate()
.get("project.hibernate.Users", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
}
Now I wrote a test class(not a junit test) to test is everything working, my user has these fields in the database : userID which is 5characters long string and unique/primary key, and fields such as address, dob etc(total 15 columns in database table). Now in my test class I intanciated User added the values like :
User user = new User;
user.setAddress("some address");
and so I did for all 15 fields, than at the end of assigning data to User object I called in DAO to save that to database UsersDao.save(user); and save works just perfectly. My question is how do I update/delete users using the same logic?
Fox example I tried this(to delete user from table users):
User user = new User;
user.setUserID("1s54f"); // which is unique key for users no two keys are the same
UsersDao.delete(user);
I wanted to delete user with this key but its obviously different can someone explain please how to do these. thank you
UPDATE :
Do I need to set all 15 fields on User object to delete it like I did with save method ?
Having not looked at Hibernate for quite a while now, I can only hazard a guess at the problem.
It seems that you are creating a User object, but only populating the User ID field, so the persistence layer knows nothing about the actual User.
I would recommend using a retrieve function that can find the User with the given ID, and then pass that User into the delete method.
User u = UsersDao.findById("1s54f");
UsersDao.delete(u);
This should work, as the persistence layer will know about the User, so it has all of the details it needs to perform the delete.
However, a more efficient method would be to find a way of deleting a user by ID, so you do not have to query the database to get the instance of the User and then delete it.
Hope this helps.
Chris
In an ideal world you will have your model's business key as the database primary key and you'll not have this problem. But it ain't so, isn't it?
For you particular problem if you are very much sure that the userID is going to be unique then you can try this (taken from here):
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlDelete = "delete User u where u.userID = :id";
int deletedEntities = s.createQuery( hqlDelete )
.setString( "id", userID )
.executeUpdate();
tx.commit();
session.close();
But let me warn you. This kind of code is not good at all. For example what happens if you decide in future that the column you used in delete is no longer unique? Then you'll run into a very serious bug or a very bad case of refactoring. Either way the fool-proof (may not be efficient & may not be feasible) way is to delete records based on their primary key.
Check out the documentation. Get used to the concept of persistent, transient, and detached instances. To delete an instance, you call
session.delete(persistentInstance)
and to update (although you probably shouldn't need to use it), call
persistentInstance = session.merge(detachedInstance)
Shouldn't need to use update? No, because you just need to load/find an object first, and then modify it. Any modifications you make to a persistent object will automatically be saved back to the database.
In order to delete the user that its ID is "1s54f" you should create a delete HQL as follows:
public void delete(String id) {
log.debug("deleting Users instance");
try {
final String deleteQuery = "delete from User where id = :id";
final Query query = getSession().createQuery(deleteQuery);
final query.setString("id",id);
final int rowCount = query.executeUpdate(); // check that the rowCount is 1
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
Then you can use this method like:
userDao.delete("1s54f");
Hope this helps.
Hibernate is an object-relational mapper, that is, it translates between the world of relational databases and object-oriented Java code. Since primary keys are a database concept, it is hibernate's job to translate them into object-oriented terms (in this case: object identity).
That is, if you pass primary keys to hibernate, you are not using hibernate as intended; calling code should represent persistent data with mapped objects, not primary keys. This also allows hibernate to automatically guard against lost updates by checking version numbers.
The typical pattern therefore is to have the following signature:
interface UserDAO {
void delete(User user);
}
and require the DAOs caller to come up with a persistent object to pass to it. The caller might have such an object lying about from the current or a previous (now closed) session, after all, he did somehow learn about its primary key. If all else fails, you can use session.load(User.class, id) to ask hibernate for a proxy to pass to the delete method. (Note that one shouldn't use session.load if the object might no longer exist in the database.)
It's not necessary fetch a whole entity before removing it, neither create a hardcoded query for delete, nor setting every field in entity.
Maybe better way to do that is setting the id for entity and use Hibernate API itself.
If a specific dao is used to entity User, as described in question, try:
public void remove(Serializable id) throws InstantiationException, IllegalAccessException {
User user = new User();
getSessionFactory().getClassMetadata(getEntityClass()).setIdentifier(user, id, (SessionImplementor) getSessionFactory().getCurrentSession());
getHibernateTemplate().delete(entity);
}
As can be seen, neither unnecessary operation in database is made.
And this can be used in generic flavor if GenericDao is implemented like:
public void remove(Serializable id) throws InstantiationException, IllegalAccessException {
Model entity = entityClass.newInstance();
getSessionFactory().getClassMetadata(getEntityClass()).setIdentifier(entity, id, (SessionImplementor) getSessionFactory().getCurrentSession());
getHibernateTemplate().delete(entity);
}
Both ways, Dao must extend org.springframework.orm.hibernate4.support.HibernateDaoSupport to get advantages.
Here's a fragment of generic:
public class GenericDaoImpl<Model> extends HibernateDaoSupport implements GenericDao<Model> {
private Class<Model> entityClass;
public GenericDaoImpl() {
this.entityClass = (Class<Model>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
/* CRUD are implemented here */
public void remove(Serializable id) throws InstantiationException, IllegalAccessException {
Model entity = entityClass.newInstance();
getSessionFactory().getClassMetadata(getEntityClass()).setIdentifier(entity, id, (SessionImplementor) getSessionFactory().getCurrentSession());
getHibernateTemplate().delete(entity);
}
}

Categories

Resources