Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

메모장

JPA Entity > Repository 본문

Java

JPA Entity > Repository

doopang 2022. 9. 30. 14:08

Entity

@Getter
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Table(name = "info")

public class Info {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "info_seq", length = 11)
  private Integer infoSeq;

  @Column(name = "a")
  private String a;

  @Column(name = "b")
  private String b;

  @Column(name = "c")
  private String c;

  @Column(name = "d")
  private String d;
}

 

DTO

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class InfoDTO implements Serializable {

  private Integer infoSeq;
  private String a;
  private String b;
  private String c;
  private String d;

  // 모든 변수 사용 시 @AllArgsConstructor 삭제
  @QueryProjection
  public InfoDTO(Integer infoSeq, String a, String b, String c) {
    this.infoSeq = infoSeq;
    this.a = a;
    this.b = b;
    this.c = c;
  }
}

 

Repository

방법1.

@Repository
public interface InfoRepository extends JpaRepository<Info, Integer>, InfoRepositoryCustom {

}
public interface InfoRepositoryCustom {
  InfoDTO findInfoByA(String A);
}
public class InfoRepositoryCustomImpl implements InfoRepositoryCustom {
  private final JPAQueryFactory jpaQueryFactory;

  public InfoRepositoryCustomImpl(EntityManager em) {
    this.jpaQueryFactory = new JPAQueryFactory(em);
  }

  public InfoDTO findInfoByA(String a) {
    return jpaQueryFactory
        .select(new QInfoDTO(info.infoSeq, info.a, info.b, info.c))
        .from(info)
        .where(info.a.eq(a))
        .fetchOne();
  }
}

 

방법2.

@Repository
public interface InfoRepository extends JpaRepository<Info, Integer> {

}
@Repository
public class InfoQueryRepository {
  private final JPAQueryFactory jpaQueryFactory;

  public InfoQueryRepository(EntityManager em) {
    this.jpaQueryFactory = new JPAQueryFactory(em);
  }

  public InfoDTO findInfoByA(String a) {
    return jpaQueryFactory
        .select(new QInfoDTO(info.infoSeq, info.a, info.b, info.c))
        .from(info)
        .where(info.a.eq(a))
        .fetchOne();
  }
}

'Java' 카테고리의 다른 글

JPA @PrePersist, @PreUpdate  (0) 2022.11.22
엑셀 POI  (0) 2022.11.10
JPA Transaction 분리하고 싶을 때  (0) 2022.04.10
JPA delete 다음에 insert 하기  (0) 2022.04.10
JPA 즉시 로딩과 지연 로딩  (0) 2022.02.02