我是基于 Java EE 的项目的链接条件查询,但我不确定这是否是一个好习惯。
有很多优点,比如它减少了代码,更重要的是可以重用初始查询。但我不知道它的缺点是什么。
请看一次并建议我是否走在正确的轨道上。它在我的项目中运行良好。
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
protected CriteriaQuery<T> criteriaQuery;
protected CriteriaBuilder criteriaBuilder;
protected Root<T> from;
protected List<Predicate> predicates;
@PostConstruct
protected void _startQuery() {
this.criteriaBuilder = getEntityManager().getCriteriaBuilder();
this.criteriaQuery = this.criteriaBuilder.createQuery(entityClass);
from = this.criteriaQuery.from(entityClass);
predicates = new ArrayList<Predicate>();
}
……………………………………………………………………………………………………………………………… ..
}
public abstract class AbstractUserLoggableFacade<T extends AbstractUserLoggable> extends AbstractFacade<T> {
.................
}
public abstract class OrganizationTrackableFacade<T extends OrganizationalTrackable> extends AbstractUserLoggableFacade<T> {
........................
}
最后是实现类。
@Stateless
public class DayStartFacade extends OrganizationTrackableFacade<DayStart> {
@TransactionAttribute(TransactionAttributeType.NEVER)
private DayStartFacade filterByEnded(Boolean b) {
this.predicates.add(criteriaBuilder.equal(from.get(DayStart_.isEnded), b));
return this;
}
@TransactionAttribute(TransactionAttributeType.NEVER)
private DayStartFacade filterByOrganization(Organization o) {
this.predicates.add(criteriaBuilder.equal(from.get(OrganizationalTrackable_.organizationId), o));
return this;
}
这是我的链式方法。以这种方式链接是一个好习惯吗?
public DayStart getCurrentDayStart() {
DayStart d = null;
try {
d = ((DayStartFacade) this.startQuery()).filterByEnded(Boolean.FALSE).filterByOrganization(userBean.getCurrentOrganization()).getSingleResult();
} catch (javax.persistence.NonUniqueResultException e) {
System.out.println("No unique restult exception at getCurrentDayStart");
e.printStackTrace();
} catch (javax.persistence.NoResultException nre) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return d;
}
}
我正在使用 JPA 2.0、Hibernate 和 GlassFish。