@Entity
어노테이션을 사용하여 정의한다.@Id
어노테이션으로 Primary Key를 정의한다.엔티티의 상태는 엔티티 매니저를 통해 변경된다. 엔티티 매니저의 persist() 메소드를 호출하면 Transient 상태에서 Persistent 상태로, remove() 메소드를 호출하면 Persistent 상태에서 Removed 상태로, detach() 메소드를 호출하면 Persistent 상태에서 Detached 상태로 변경된다.
@Entity
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
// getter, setter, constructor
}
EntityManager em = entityManagerFactory.createEntityManager();
String jpql = "SELECT m FROM Member m WHERE m.age > :age";
List<Member> members = em.createQuery(jpql, Member.class)
.setParameter("age", 20)
.getResultList();
위 코드는 Member 엔티티에서 나이(age)가 20 이상인 회원을 조회하는 JPQL입니다. JPQL은 엔티티 객체를 대상으로 쿼리를 작성하므로, "Member"라는 엔티티 객체를 대상으로 "m"이라는 별칭을 사용하여 조회합니다.
JPQL은 SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY 등의 기능을 지원합니다. 이 코드에서는 SELECT와 WHERE 절을 사용하였습니다. SELECT 절에서는 "m"이라는 별칭을 사용하여 Member 엔티티의 모든 필드를 조회합니다. WHERE 절에서는 "m.age > :age"라는 조건을 사용하여, 나이가 20 이상인 회원을 조회합니다.
JPQL을 실행하기 위해, EntityManager의 createQuery() 메서드를 사용하여 JPQL 문자열과 반환 타입을 지정합니다. 그리고 setParameter() 메서드를 사용하여 JPQL에 사용되는 파라미터 값을 지정합니다. 이후에 getResultList() 메서드를 호출하여 조회 결과를 반환합니다.
JPA에서 Transaction은 EntityManager를 통해 제어된다. EntityManager는 트랜잭션을 시작하고 커밋 또는 롤백하는 메서드를 제공한다. 트랜잭션은 다음과 같은 방식으로 사용된다.
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
// 엔티티를 수정, 추가, 삭제하는 작업을 수행한다.
// ...
transaction.commit();
} catch (Exception e) {
if (transaction.isActive()) {
transaction.rollback();
}
} finally {
entityManager.close();
}
객체와 테이블 매핑(Objcet-Relational)
객체와 테이블 간의 매핑을 정의한다. 이러한 매핑을 통해 객체를 데이터베이스에 저장하고 조회할 수 있다. 대표적인 어노테이션으로는 @Entity, @Table, @Column 등이 있다.
연관관계 매핑(Objcet-Objcet)
객체와 객체 간의 관계를 정의한다. 객체 간의 관계를 테이블 간의 관계로 변환하여 데이터베이스에 저장하고 조회할 수 있다. 대표적인 어노테이션으로는 @OneToOne, @OneToMany, @ManyToOne, @ManyToMany 등이 있다.
Entity의 상태 변화에 따라 호출되는 메서드를 정의하는 방법이다. 즉, Entity의 상태 변화가 발생할 때마다 특정 메서드를 자동으로 호출하여 개발자가 원하는 작업을 수행할 수 있도록 한다.
이러한 Callback Methods는 주로 Entity의 상태 변화에 따른 보조 작업을 수행하기 위해 사용된다. 예를 들어, 데이터베이스에 저장되기 전에 입력값을 검증하거나, 저장 시간을 기록하거나, 삭제 시 관련 데이터를 함께 삭제하는 등의 작업을 수행할 수 있다.
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
@Transient
private boolean modified;
@PrePersist
public void prePersist() {
System.out.println("prePersist() called");
}
@PostPersist
public void postPersist() {
System.out.println("postPersist() called");
}
@PreUpdate
public void preUpdate() {
System.out.println("preUpdate() called");
}
@PostUpdate
public void postUpdate() {
System.out.println("postUpdate() called");
}
@PreRemove
public void preRemove() {
System.out.println("preRemove() called");
}
// getter, setter, constructor 생략
}