2014-02-21 4 views
0

JPA로 내 데이터베이스에 액세스하려면 일반 구현의 추상 기본 클래스를 사용합니다. 엔티티 메타 모델도 사용합니다.메타 모델 클래스의 필드를 일반적인 방법으로 확인하는 방법은 무엇입니까?

public List<PersonEntity> findByCode(String code) { 
    CriteriaBuilder cb = entityManager.getCriteriaBuilder(); 
    CriteriaQuery<PersonEntity> cq = cb.createQuery(PersonEntity.class); 
    Root<PersonEntity> root = cq.from(PersonEntity.class); 

    Predicate predicate = cb.equal(root.get(PersonEntity_.code), code); 
    cq.where(predicate); 

    TypedQuery<PersonEntity> query = entityManager.createQuery(cq); 
    List<PersonEntity> list = new ArrayList<>(); 
    return query.getResultList(); 
} 

이 코드의 평화는 많은 시간을 사용하기 때문에 이것을 일반 기본 클래스로 옮기고 싶습니다. "코드"가 있는지 어떻게 확인합니까? 모든 수업에 하나가있는 것은 아닙니다.

public List<E> findByCode(String code) { 
    CriteriaBuilder cb = entityManager.getCriteriaBuilder(); 
    CriteriaQuery<E> cq = cb.createQuery(entityClass); 
    Root<E> root = cq.from(entityClass); 

    //here is my problem: how to check if there is a "code"? 
    // Most classes have one, but not all. 
    Predicate predicate = cb.equal(root.get(PersonEntity_.code), code); 
    cq.where(predicate); 

    TypedQuery<E> query = entityManager.createQuery(cq); 
    List<E> list = new ArrayList<>(); 
    return query.getResultList(); 
} 

답변

1
당신은 아마 (더 나은 이름) ​​인터페이스 선언해야

:

public interface Codeable { 
    public String getCode(); 
} 

을 그리고 다음과 같은 방법을 선언

public List<E implements Codeable> findByCode(String code, Class<E> clazz) { 
    CriteriaBuilder cb = entityManager.getCriteriaBuilder(); 
    CriteriaQuery<E> cq = cb.createQuery(entityClass); 
    Root<E> root = cq.from(entityClass); 

    //here is my problem: how to check if there is a "code"? 
    // Most classes have one, but not all. 
    Predicate predicate = cb.equal(root.get(PersonEntity.getCode()), code); 
    cq.where(predicate); 

    TypedQuery<E> query = entityManager.createQuery(cq); 
    List<E> list = new ArrayList<>(); 
    return query.getResultList(); 
} 

당신은 매개 변수 clazz 당신 클래스 유형에 전달을 (컴파일러가 쿼리에서 실제로 사용할 형식과 반환 할 형식을 알기 위해)

List<PersonEntity> persons = dao.findByCode("someCode", PersonEntity.getClass()); 

P.S

는 또한 인터페이스를 준수하기 위해 .getCode().code을 변경했습니다.