Cambridge Technology PartnersCommunity Documentation
While CDI Query defines several base interfaces, there might still be one or another convenience method that is missing. This is actually intentional - things should not get overloaded for each and every use case. That's why in CDI Query you can define your own reusable methods.
For example, you might want to refresh an entity immediately after you've flushed it to the database (e.g. because a trigger fired and updated your entity). You might want to define the following method on a base DAO:
public E saveAndRefresh(E entity) {
entityManager.persist(entity);
entityManager.flush();
entityManager.refresh(entity);
return entity;
}
This method is generic enough that you can use it in all your DAOs. You can now mixin this method in your DAOs with a simple mechanism.
The first step is to define an interface which contains all the extra methods for your DAOs:
public interface DaoExtension<E> {
E saveAndRefresh(E entity);
}
As a next step, you need to provide an implementation for this interface
once. It's also important that this implementation implements the
DelegateQueryHandler
interface (don't worry, this is)
just an empty marker interface):
public class DelegateDaoExtension<E> implements DaoExtension<E>, DelegateQueryHandler {
@Inject
private QueryInvocationContext context;
@Override
public E saveAndRefresh(E entity) {
entityManager().persist(entity);
entityManager().flush();
entityManager().refresh(entity);
return entity;
}
private EntityManager entityManager() {
return context.getEntityManager();
}
}
As you see in the sample, you can inject a QueryInvocationContext
which contains utility methods like accessing the current
EntityManager
and entity class.
To use your newly created functionality, your DAOs can now be written like
@Dao
public interface SimpleDao extends DaoExtension<Simple>, EntityDao<Simple, Long> {
}
Note that, if you define multiple extensions with equivalent method signatures, there is no specific order in which the implementation is selected.
CDI Query contains basic support for the Querydsl framework for JPA. Implementing
the QueryDslSupport
interface (and including the Querydsl
dependencies) gives you access to a JPAQuery
handle.
You can find more information about Querydsl on the website.