JPA/JPA 22

JPA TOP1 사용법

방법 1. FirstN, TopN을 통해 TOPN 쿼리를 호출한다. @Repository public interface AaaRepository extends JpaRepository { AaaEntity findTop1ByFlagEqualsOrderByCreatedAtDesc(Integer flag); AaaEntity findFirst1ByFlagEqualsOrderByCreatedAtDesc(Integer flag) } 방법 2. Pageable을 사용하여 Top 쿼리를 호출한다. 호출 후 List.get(0)을 사용해서 가져와야한다. 해당 방법은 JPQL 사용시에도 동일하게 적용된다. @Repository public interface AaaRepository extends JpaRepositor..

JPA/JPA 2021.03.15

JPA Enum Mapping

JPA 사용시 컬럼값에 Enum을 자동 매핑하기 위한 방법을 소개한다. Enum에서 상속받는 interface 구현 public interface BaseEnumCode { T getValue(); } Enum 클래스 생성 @Getter @AllArgsConstructor public enum ContentSourceEnum implements BaseEnumCode { news("뉴스", "news"), videoNews("포토/동영상 뉴스", "videoNews"), normal("일반", "normal"); private String name; private String value; } Code 값을 Enum으로 자동 매핑해주는 클래스 생성 public abstract class AbstractBa..

JPA/JPA 2021.03.15

insert, update, delete 주의 사항(쿼리 실행 순서)

쿼리 동작 우선 순위 Hibernate는 영속성 컨텍스트에 등록된 쿼리에 대해 아래와 같은 우선 순위에 맞춰 쿼리가 실행되도록 되어있다. 로직을 다음과 같이 구현하는 경우 flush를 반드시 사용해야 원하는 대로 동작한다. find, remove, update, insert 순으로 로직이 구현된 경우 > Hibernate는 find, update, insert, remove 순서로 쿼리를 실행하므로 원하지 않는 결과가 발생한다. 쿼리 실행 순서 1. Inserts, in the order they were performed 2. Updates 3. Deletion of collection elements 4. Insertion of collection elements 5. Deletes, in the o..

JPA/JPA 2020.11.11

SAVE 메서드 주의 사항

새로운 엔티티인 경우 저장 새로운 엔티티가 아닌 경우 MERGE 함 *** @GeneratedValue 인 경우 식별자가 없을 경우 SAVE 가 호출되나 @Id 만 사용한 경우 식별자가 있는 것으로 간주하여 SELECT SAVE가 호출된다. 매우 비효율적이므로 implements Persistable의 isNew를 구현하여 직접 SAVE가 호출되도록 할 수 있다. @Entity @Getter @EntityListeners(AuditingEntityListener.class) @NoArgsConstructor(access = AccessLevel.PROTECTED) public class Item implements Persistable { @Id private String id; @CreatedDate ..

JPA/JPA 2020.06.09

사용자 정의 리포지토리 구현

화면 조회시 사용되는 복잡한 쿼리들은 기존 리포지토리를 사용하지 말고, 새로운 리포지토리를 생성하여 사용 권장 // 기능 인터페이스 생성 public interface MemberRepositoryCustom { List findMemberCustom(); } // 인터페이스 구현 @RequiredArgsConstructor public class MemberRepositoryImpl implements MemberRepositoryCustom { // 이름을 맞춰야함 class명 + impl private final EntityManager em; // 주입 권장방식 @Override public List findMemberCustom() { return em.createQuery("select m f..

JPA/JPA 2020.06.09

페이징 처리

**페이지수는 0부터 시작한다 public interface MemberRepository extends JpaRepository { // 기본 페이징 처리(totalcnt 조회 가능) Page findByAge(int age, Pageable pageable); // 가져오려는 수보다 +1 더 가져와 구현 가능(totalcnt 없음), 모바일 device에서 구현할때 사용함.(미리 로딩 가능) Slice findByAge(int age, Pageable pageable); // 카운트 쿼리를 분리해서 사용이 가능하다. @Query(countQuery = "") ... } // 구현부 int page = 0; int limit = 3; PageRequest pageRequest = PageRequest...

JPA/JPA 2020.06.09

Auditing

엔티티 생성, 변경할 때 변경한 사람과 시간을 알고 싶은 경우 Main class에 @EnableJpaAuditing 추가 등록일 수정일 등록자 수정자 @EntityListeners(AuditingEntityListener.class) @MappedSuperclass public class JpaBaseEntity { @CreatedDate @Column(updatable = false) private LocalDateTime createdDate; @LastModifiedDate private LocalDateTime lastModifiedDated; @CreatedBy @Column(updatable = false) private String createdBy; @LastModifiedBy priva..

JPA/JPA 2020.06.09

컬렉션 조회(OneToMany)

Fetch 조인 사용시 페이징 처리는 하지 말것. 모든 데이터 조회 이후 메모리에서 페이징 처리하므로 큰 장애가 발생할 수 있음. Fetch 조인 페이징 처리 방법 XtoOne 관계는 모두 Fetch 조인 컬렉션은 지연 로딩으로 조회 fetch 조인 로딩값 개수 설정 spring: jpa: properties: hibernate: default_batch_fetch_size: 100 // in 쿼리 갯수 lazy 로딩 값 한번에 호출 복합키는 복합키 클래스를 생성해서 처리해야함.

JPA/JPA 2020.06.09