kwonslog / how-to-use-jpa

0 stars 0 forks source link

JPA 기본 및 사용법 #5

Closed kwonslog closed 1 month ago

kwonslog commented 5 months ago

기본

## 사용법
- 트랙잭션 안에서 사용해야 하며 객체의 값을 변경하면 트랜잭션이 끝나기 전에 자동으로 쿼리를 만들어서 실행한다.

### insert

EntityManagerFactory emf = Persistence.createEntityManagerFactory("example-unit"); EntityManager em = emf.createEntityManager();

EntityTransaction tx = em.getTransaction(); tx.begin();

try { User newUser = new User(); newUser.setUsername("새로운유저"); newUser.setEmail("newuser@example.com");

em.persist(newUser);

tx.commit();

} catch (Exception e) { if (tx.isActive()) { tx.rollback(); } e.printStackTrace(); } finally { em.close(); emf.close(); }

### update

EntityManagerFactory emf = Persistence.createEntityManagerFactory("example-unit"); EntityManager em = emf.createEntityManager();

EntityTransaction tx = em.getTransaction(); tx.begin();

try { // 업데이트할 User 엔티티를 조회합니다. Long userIdToUpdate = 1L; // 업데이트할 User의 ID User userToUpdate = em.find(User.class, userIdToUpdate);

if (userToUpdate != null) {
    // 필드 값을 업데이트합니다.
    userToUpdate.setUsername("새로운유저이름");
    userToUpdate.setEmail("newemail@example.com");

    // 엔티티 매니저가 자동으로 업데이트를 감지하고 데이터베이스에 반영합니다.
}

tx.commit();

} catch (Exception e) { if (tx.isActive()) { tx.rollback(); } e.printStackTrace(); } finally { em.close(); emf.close(); }

### delete

EntityManagerFactory emf = Persistence.createEntityManagerFactory("example-unit"); EntityManager em = emf.createEntityManager();

EntityTransaction tx = em.getTransaction(); tx.begin();

try { // 삭제할 User 엔티티를 조회합니다. Long userIdToDelete = 1L; // 삭제할 User의 ID User userToDelete = em.find(User.class, userIdToDelete);

if (userToDelete != null) {
    // 엔티티 매니저를 사용하여 엔티티를 삭제합니다.
    em.remove(userToDelete);
}

tx.commit();

} catch (Exception e) { if (tx.isActive()) { tx.rollback(); } e.printStackTrace(); } finally { em.close(); emf.close(); }