메모장
JPA Entity > Repository 본문
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 |