봉 블로그

Spring JPA 에서 POJO 사용하기 본문

java

Spring JPA 에서 POJO 사용하기

idkbj 2016. 9. 22. 17:26

Spring JPA 를 사용하면서 특정 Entity 와는 다른 데이타(field 조합)를 쿼리할경우가 있다.

또는

Entity 의 특정 field 만 쿼리할경우는 아래와 같이 하면 된다.


----------- 아래는 Entity class 를 사용하는경우 ---------

@Repository

public interface BoardRepository extends JpaRepository<Board, Integer>, JpaSpecificationExecutor<Board> {


@Query(value = "SELECT new Board(b.id, b.subject, b.userId, b.createDt) FROM Board b")

Page<Board> findList(Pageable pageable);

}


----------- 아래는 POJO class 를 사용하는경우 ---------


@Query(value = "SELECT new com.bong.bbs.BoardRow(b.id, b.subject, b.userId, b.createDt) FROM Board b")

Page<BoardRow> findList(Pageable pageable);



-------- 아래 생성자가 있어야 함. BoardRow 도 마찬가지 ---


public Board(Integer id, String subject, Long userId, Date createDt) {

super();

this.id = id;

this.subject = subject;

this.userId = userId;

this.createDt = createDt;

}



@SqlResultSetMapping 를 사용할수도 있지만 복잡하다.


native query 결과를 pojo 로 리턴받고 싶다면 @SqlResultSetMapping 를 사용하는것이 좋겠다.