티스토리 뷰

Querydsl을 사용해서 Entity-> DTO에 Projections.constructor를 사용해 projection 하던 중 

org.hibernate.QueryException: not an entity 문제가 발생

 @Override
    public Page<TodoDto.GetAllTodo> findAllTodosByCreatedDate(Pageable pageable){

        List<TodoDto.GetAllTodo> content=queryFactory
                .select(new QTodoDto_GetAllTodo(todo.todoId,
                        todo.title,
                        todo.description,
                        todo.tags,
                        todo.isCompleted,
                        todo.createdAt,
                        todo.updatedAt))
                .where(isDeletedCheck())
                .orderBy(todo.createdAt.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetch();

        JPAQuery<Todo> count=queryFactory
                .selectFrom(todo)
                .where(isDeletedCheck())
                .orderBy(todo.createdAt.desc());

        return PageableExecutionUtils.getPage(content, pageable, ()->count.fetchCount());
    }
public class Todo{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer todoId;

    private String title;

    private String description;

    private boolean isCompleted;

    private boolean isDeleted;

    private LocalDateTime createdAt;

    @ElementCollection
    private List<String> tags=new ArrayList<>();

    private LocalDateTime updatedAt;

    @OneToMany(mappedBy="todo")
    private List<Comment>comments= new ArrayList<>();

    @Builder
    public Todo(String title, String description){
        this.title=title;
        this.description=description;
    }

}

이때 ElementCollection 으로 사용되었으므로  별도의 테이블(todo_tags)에 저장되어 있어  todo.tags로는 데이터가  불러오지 않는 것이다.

 

방법 1) todo를 comments처럼 OneToMany로 일대다 관계 엔티티를 만든 다음 영속성 전이 + 고아 객체 제거를 사용해 값 타입 컬렉션처럼 사용

방법 2) java stream 함수를 이용해 List<Todo>-> List<Dto>로 바꾸어준다.

  @Override
    public Page<TodoDto.GetAllTodo> findAllTodosByCreatedDate(Pageable pageable){
    
                List<Todo> content2=queryFactory
                .selectFrom(todo)
                .where(isDeletedCheck())
                .orderBy(todo.createdAt.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetch();

        List<TodoDto.GetAllTodo> content=content2.stream().map(c->new TodoDto.GetAllTodo(c.getTodoId(),c.getTitle(),c.getDescription(),c.getTags(),c.isCompleted(),c.getCreatedAt(),c.getUpdatedAt())).collect(Collectors.toList());

        JPAQuery<Todo> count=queryFactory
                .selectFrom(todo)
                .where(isDeletedCheck())
                .orderBy(todo.createdAt.desc());

        return PageableExecutionUtils.getPage(content, pageable, ()->count.fetchCount());
    }