Programming/Java

JPA 사용법

armyost 2023. 10. 11. 10:29
728x90

Hexagonal Architecture, Clean Architecture가 뜨면서 JAVA와 Python에도 어플리케이션의 Repository, Entity 정의가 필요해지고 있다. 

 

Git 주소 : https://github.com/armyost/jpaJoinSample

 

GitHub - armyost/jpaJoinSample

Contribute to armyost/jpaJoinSample development by creating an account on GitHub.

github.com

 

JPA는 Entity, Repository가 필요하다. Repository는 일종의 Entity에 대한 연산을 위한 인터페이스 이다.

JPA가 필요한 이유는.. 요즘에는 워낙 다양한 데이터저장소가 있다보니 다양한 타입의 데이터 통합을 Application Layer 에서 하려면 기본적으로 Application Layer에 Entity가 있어줘야하기때문이다. 그리고 Adaptor 형태로 Service Layer에 제공하게 되면 개발자 종속성도 줄고, 유지관리 측면에서도 좋다.

 

Entity 정의 : Class 로 정의하고 @Entity를 붙인다

@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Department {
    private static final Logger logger = LoggerFactory.getLogger(Department.class);

    @Id
    @Column(name = "deptId")
    private Long deptId;

    @OneToMany(mappedBy = "department")
    private List<User> user = new ArrayList<User>();

    @CreationTimestamp
	@Column(name = "createTime")
	private LocalDateTime createTime;
    
    private String deptName;    
    private String deptDescription;
}
@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private static final Logger logger = LoggerFactory.getLogger(User.class);

    @Id
    @Column(name = "userId")
    private Long userId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "deptId")
    private Department department; 
    
    private String userName;    
    private String userDescription;

    @CreationTimestamp
	@Column(name = "createTime")
	private LocalDateTime createTime;
}

 

Repository를 정의한다.

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    String SELECT_USER_BY_USERID = "select " +
            "distinct new map( u.userId as userId, u.userName as userName, d.deptName as departmentName) " +
            "from User u " +
            "join u.department d " +
            "where u.userId = :userId";

    @Query(value = SELECT_USER_BY_USERID)
    Map <String, Object> findUserbyUserId(@Param("userId") Long userId);

    Optional<User> findById(Long userId);
}
@Repository
public interface DepartmentRepository extends JpaRepository<Department, Long>{
}

이때, JPA API를 사용하거나, JPQL 을 사용하는 방법 두가지 가 있으며, JPQL은 SQL과 유사한 친숙성이 있지만, JPA API는 친숙도 보다는 객체로 접근하는 형태라서 확장성이 좋다.

 

JPQL 관련 링크

https://en.wikibooks.org/wiki/Java_Persistence/JPQL

 

Java Persistence/JPQL - Wikibooks, open books for an open world

The Java Persistence Query Language (JPQL) is the query language defined by JPA. JPQL is similar to SQL, but operates on objects, attributes and relationships instead of tables and columns. JPQL can be used for reading (SELECT), as well as bulk updates (UP

en.wikibooks.org

 

JPA Reference Document

https://en.wikibooks.org/wiki/Java_Persistence/JPQL

 

Java Persistence/JPQL - Wikibooks, open books for an open world

The Java Persistence Query Language (JPQL) is the query language defined by JPA. JPQL is similar to SQL, but operates on objects, attributes and relationships instead of tables and columns. JPQL can be used for reading (SELECT), as well as bulk updates (UP

en.wikibooks.org