2

I require adding a little intelligence to the JPA EntityManager, customizing the createNamedQuery. I'm working in a project build of many modules, where every module annotates its instance of EntityManager with @PersistenceContext(unitName = "emModuleName").

It seems that I cannot simply extends the interface EntityManager, but I don't find any documentation about this matter online.

Does anyone has an idea what is the best solution for my needs?

I cannot extend one specific implementation because the application has to be JPA implementation independent. Thanks

1
  • Since each JPA provider IMPLEMENTS EntityManager with their own class, and since you say you cannot extend an implementation, then you cannot do that. Commented Nov 9, 2016 at 15:04

2 Answers 2

1

One way would be to create own implementation of EntityManager that would act as a wrapper to real EnityManager. Intercept required method (in your case createNamedQuery), and delegate every other call to underyling object.

OR

Create your own proxies to intercept method calls.

Both ways however are not that trivial to use as you probably would like it to be.

Sign up to request clarification or add additional context in comments.

Comments

0

You can create a BaseEntitymanager which provides a base implementation for basic CRUD services and the respective DAO has to extend the BaseEntityManager.

BaseEntityManager:

public interface EntityManagerBase<E, K> {
    E create(E entity);
    void delete(E entity);
    E update(E entity);
}

EntityManagerBaseImpl

    public abstract class EntityManagerBaseImpl<E, K> implements
        EntityManagerBase<E, K> {

    private EntityManager entityManager;

    private TransactionManager txManager;

    private Class<E> type;

    public E create(E entity) {     
        entityManager.persist(entity);
        entityManager.flush();
        return entity;
    }

MyDaoImpl:

public class MyDaoImpl extends EntityManagerBaseImpl<MyDBO, Long> implements MyDao {
//put your implementation of methods
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.