복붙노트

[SPRING] 봄 데이터 JPA - 개체를 반환하는 가장 좋은 방법은?

SPRING

봄 데이터 JPA - 개체를 반환하는 가장 좋은 방법은?

나는 이런 물건을 가지고있다 :

@Entity
public class DocumentationRecord {
    @Id
    @GeneratedValue
    private long id;

    private String topic;
    private boolean isParent;
    @OneToMany
    private List<DocumentationRecord> children;
...
}

지금은 주제와 ID 만 받고 싶습니다. 다음과 같은 형식으로 가져올 수 있습니까?

[
{
id: 4234234,
topic: "fsdfsdf"
},...
]

이 쿼리 만 사용하기 때문에

public interface DocumentationRecordRepository extends CrudRepository<DocumentationRecord, Long> {

    @Query("SELECT d.topic as topic, d.id as id FROM DocumentationRecord d")
    List<DocumentationRecord> getAllTopics();
}

나는 이렇게 기록을 낼 수있었습니다 :

[
  [
    "youngChild topic",
    317
  ],
  [
    "oldChild topic",
    318
  ],
  [
    "child topic",
    319
  ],
]

나는 배열의 배열을 좋아하지 않는다. 속성 id와 topic을 가진 객체의 배열을 얻고 싶다. 그것을 달성하는 가장 좋은 방법은 무엇입니까?

해결법

  1. ==============================

    1.Spring Data JPA에서는 투영법을 사용할 수 있습니다.

    Spring Data JPA에서는 투영법을 사용할 수 있습니다.

    인터페이스 기반 :

    public interface IdAndTopic {
        Long getId();
        String getTopic();
    }
    

    수업 기반 (DTO) :

    @Value // Lombok annotation
    public class IdAndTopic {
       Long id;
       String topic;
    }
    

    그런 다음 저장소에 간단한 쿼리 메소드를 만듭니다.

    public interface DocumentationRecordRepository extends CrudRepository<DocumentationRecord, Long> {
    
        List<IdAndTopic> findBy();
    }
    

    동적 쿼리 방법을 만들 수도 있습니다.

    List<T> findBy(Class<T> type);
    

    다음과 같이 사용하십시오.

    List<DocumentationRecord> records = findBy(DocumentationRecord.class);
    List<IdAndTopic> idAndTopics = findBy(IdAndTopic.class);
    
  2. ==============================

    2.id와 topic 속성을 가진 클래스를 생성하고 생성자 삽입을 쿼리에 사용할 수 있습니다. Sth는 아래처럼

    id와 topic 속성을 가진 클래스를 생성하고 생성자 삽입을 쿼리에 사용할 수 있습니다. Sth는 아래처럼

    @Query("SELECT NEW your.package.SomeObject(d.id, d.topic) FROM DocumentationRecord d")
    
  3. from https://stackoverflow.com/questions/46878292/spring-data-jpa-the-best-way-to-return-object by cc-by-sa and MIT license