2013-02-20 2 views
3

Person 클래스에 해당하는 테이블에 다음 데이터가 있다고 가정하면 name1name2 필드의 연결에 대해 안전하게 안전하게 null을 검색하는 올바른 방법은 무엇입니까? 기본적으로 Querydsl null-safe 연결

 
id | name1 | name2 
------------------------ 
1 | Foo | null 
2 | null | Bar 
3 | Foo | Bar 

@Entity 
public class Person { 
    Long id; 
    String name1; 
    String name2; 
    // Getters and setters omitted for brevity 
} 

null에서 두 개의 열 결과의는 연결은이 중 하나가 null 인 경우. 다음 목록에

위의 코드 결과 :

null 
null 
FooBar 

답변

9

쉬운 방법 중 하나가 발생합니다 Querydsl

에 해당하는
public List<String> nameConcatenations() { 
    JPAQuery q = new JPAQuery(entityManager); 
    QPerson person = QPerson.person; 
    StringExpression nameConcatenation = emptyIfNull(person.name1) 
     .concat(emptyIfNull(person.name2)); 
    return q.from(person).list(nameConcatenation) 
} 

private static StringExpression emptyIfNull(StringExpression expression) { 
    return expression.coalesce("").asString(); 
} 

이있는 SQL의 COALESCE 기능을 사용하는 것입니다 다음 목록 :

Foo 
Bar 
FooBar