I'm using inheritance with EJB in a few scenarios, sometimes with annotations in the super class like this generic entityDAO:
public class JpaDAO<T>{
protected Class<T> entityClass;
@PersistenceContext(unitName="CarrierPortalPU")
protected EntityManager em;
protected CriteriaBuilder cb;
@PostConstruct
private void init() {
cb = em.getCriteriaBuilder();
}
public JpaDAO(Class<T> type) {
entityClass = type;
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void create(T entity) {
em.persist(entity);
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public T find(Object id) {
return em.find(entityClass, id);
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public List<T> findAll(){
CriteriaQuery<T> cq = cb.createQuery(entityClass);
Root<T> entity = cq.from(entityClass);
cq.select(entity);
return em.createQuery(cq).getResultList();
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void remove(T entity) {
em.remove(em.merge(entity));
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public T edit(T entity) {
return em.merge(entity);
}
}
With an example subclass implemented like this:
@Stateless
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class DepartmentDAO extends JpaDAO<Department> {
public DepartmentDAO() {
super(Department.class);
}
public Department findByName(String name){
CriteriaQuery<Department> cq = cb.createQuery(Department.class);
Root<Department> department = cq.from(Department.class);
cq.where(cb.equal(department.get(Department_.name), name));
cq.select(department);
try{
return em.createQuery(cq).getSingleResult();
}catch(Exception e){
return null;
}
}
}
I recently read that java annotations are NOT inherited (source). This should cause my JpaDAO to throw a null pointer exception when accessing its entitymanager or its criteriabuilder (since both @PersistanceContext and @PostConstruct would be ignored), however this it not the case. Can someone clarify how this really works? I am abit worried about what happens to my @TransactionAttributes in the superclass, can I trust a REQUIRED to actually use transactions when called from the subclass, when the subclass has NOT_SUPPORTED as class default?