게으른 개발자의 끄적거림

JPA란? 기본 CRUD 예제

끄적잉 2024. 4. 29. 22:02
반응형

JPA란? 기본 CRUD 예제

 

 Java Persistence API(JPA)는 자바에서 관계형 데이터베이스와의 상호 작용을 간편하게 하기 위한 API입니다. JPA는 객체 관계 매핑(Object-Relational Mapping, ORM)을 지원하여 객체 지향 프로그래밍 언어와 관계형 데이터베이스 간의 데이터를 변환하고 매핑하는데 사용됩니다. 이것은 개발자가 데이터베이스와 직접 상호 작용하지 않고도 객체를 사용하여 데이터를 다룰 수 있도록 도와줍니다. JPA는 자바 표준 명세서이며, 다양한 ORM 프레임워크(예: Hibernate, EclipseLink)에서 구현됩니다.

 

 JPA를 사용하면 객체를 데이터베이스 테이블에 매핑할 수 있으며, 이를 통해 객체 지향 언어의 장점을 유지하면서 데이터를 영구적으로 저장하고 검색할 수 있습니다. 이를 위해 JPA는 다양한 주석(Annotations)과 XML 구성을 제공합니다. 주석을 사용하여 객체의 필드와 데이터베이스 테이블의 열을 매핑하고, 관계를 정의할 수 있습니다.

아래에는 JPA를 사용하여 간단한 예제를 보여드리겠습니다.

 

반응형

 


1. **엔티티 클래스 생성**: 먼저, 데이터베이스 테이블에 해당하는 엔티티 클래스를 생성합니다. 예를 들어, 간단한 학생 엔티티를 만들어 보겠습니다.

```java
import javax.persistence.*;

@Entity
@Table(name = "students")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

    @Column(name = "age")
    private int age;

    // Getters and setters
}
```

 

 


2. **Create (생성)**: 새로운 학생을 데이터베이스에 추가하는 과정입니다.

```java
import javax.persistence.*;

public class CreateExample {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
        EntityManager em = emf.createEntityManager();

        // 새로운 학생 생성
        em.getTransaction().begin();
        Student student = new Student();
        student.setName("Alice");
        student.setAge(21);
        em.persist(student);
        em.getTransaction().commit();

        em.close();
        emf.close();
    }
}
```

 

 


3. **Read (읽기)**: 데이터베이스에서 학생을 검색하는 과정입니다.

```java
import javax.persistence.*;

public class ReadExample {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
        EntityManager em = emf.createEntityManager();

        // 학생 검색
        Student student = em.find(Student.class, 1L);
        if (student != null) {
            System.out.println("Found student: " + student.getName());
        } else {
            System.out.println("Student not found.");
        }

        em.close();
        emf.close();
    }
}
```

 

 


4. **Update (갱신)**: 데이터베이스에서 학생을 업데이트하는 과정입니다.

```java
import javax.persistence.*;

public class UpdateExample {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        // 엔티티 가져오기
        Student student = em.find(Student.class, 1L);
        if (student != null) {
            // 필드 업데이트
            student.setName("Updated Name");
            em.merge(student); // 변경 사항 저장
            em.getTransaction().commit();
            System.out.println("Student updated successfully.");
        } else {
            System.out.println("Student not found.");
        }

        em.close();
        emf.close();
    }
}
```

 

 


5. **Delete (삭제)**: 데이터베이스에서 학생을 삭제하는 과정입니다.

```java
import javax.persistence.*;

public class DeleteExample {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        // 엔티티 가져오기
        Student student = em.find(Student.class, 1L);
        if (student != null) {
            // 엔티티 삭제
            em.remove(student);
            em.getTransaction().commit();
            System.out.println("Student deleted successfully.");
        } else {
            System.out.println("Student not found.");
        }

        em.close();
        emf.close();
    }
}
```

이제 위의 예제를 참고하여 JPA를 사용하여 간단한 CRUD 작업을 수행하는 방법을 이해할 수 있을 것입니다. JPA는 객체 지향 프로그래밍과 관계형 데이터베이스 간의 상호 작용을 간소화하고 개발자가 데이터베이스에 접근하는 방법을 표준화하는 데 큰 도움이 됩니다.

반응형

'게으른 개발자의 끄적거림' 카테고리의 다른 글

javascript each()란?  (0) 2024.05.02
Javascript filter()란?  (0) 2024.05.02
jQuery $.function 이란?  (0) 2024.04.25
Java Exception 완벽 정리  (0) 2024.04.24
jsp에서 vo받는 방법  (0) 2024.04.23