2012-04-24 2 views
4

보통 저는 Hibernate 사용자이고 새 프로젝트에서는 JPA 2.0을 사용합니다.완전히 동적으로 JPA 기준 만들기

내 DAO는 일반으로 컨테이너를받습니다.

if (">".equals(container.getOperation()) { 
    criteriaBuilder.greaterThan(root.get(container.getFieldId()), container.getValue()); 
} 

때문에 나는이 같은 유형을 지정해야합니다 :

public class Container<T> { 
    private String fieldId; // example "id" 
    private T value;   // example new Long(100) T is a Long 
    private String operation; // example ">" 

    // getter/setter 
} 

다음 줄은 컴파일되지 않습니다

if (">".equals(container.getOperation()) { 
    criteriaBuilder.greaterThan(root.<Long>get(container.getFieldId()), (Long)container.getValue()); 
} 

하지만 난 그렇게하고 싶지 않아! 내 컨테이너에 제네릭을 사용하기 때문에! 아이디어가 있습니까?

답변

4

만큼 당신의 T입니다 Comparable (이 greaterThan에 필요한 것), 다음과 같이 할 수 있어야한다 :

public class Container<T extends Comparable<T>> { 
    ... 
    public <R> Predicate toPredicate(CriteriaBuilder cb, Root<R> root) { 
     ... 
     if (">".equals(operation) { 
      return cb.greaterThan(root.<T>get(fieldId), value); 
     } 
     ... 
    } 
    ... 
}