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());
}
'Spring > JPA' 카테고리의 다른 글
[JPA] MultipleBagFetchException와 N+1문제 동시에 해결하기 (1) | 2023.09.24 |
---|---|
[JPA] entity에서 생성시간, 수정시간 반영하는 법 (1) | 2023.01.28 |
MapStruct를 이용해 Dto->Entity 변환하기 (0) | 2023.01.21 |
[JPA] 연관관계 매핑-양방향 연관관계 (0) | 2022.11.11 |