[java] 자바 ORM에서의 데이터베이스 CRUD 작업

오늘은 자바 어플리케이션에서 ORM(Object-Relational Mapping)을 사용하여 데이터베이스의 CRUD(Create, Read, Update, Delete) 작업을 실행하는 방법에 대해 알아보겠습니다.

ORM이란?

ORM은 관계형 데이터베이스와 객체 지향 프로그래밍 언어 간의 데이터 변환을 자동화하는 기술입니다. 자바에서는 대표적으로 Hibernate, JPA(Java Persistence API), MyBatis 등이 있습니다.

데이터베이스 연동 설정

자바 어플리케이션에서 ORM을 이용해 데이터베이스와 연동하기 위해 먼저 데이터베이스 접속 정보를 설정해야 합니다. 이 설정은 어플리케이션의 persistence.xml 또는 프로퍼티 파일을 통해 할 수 있습니다.

<persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL">
    <properties>
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mydatabase"/>
        <property name="javax.persistence.jdbc.user" value="username"/>
        <property name="javax.persistence.jdbc.password" value="password"/>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
    </properties>
</persistence-unit>

데이터베이스 CRUD 작업

Create (생성)

EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
EntityManager em = emf.createEntityManager();

em.getTransaction().begin();

EntityClass entity = new EntityClass();
// set entity properties
em.persist(entity);

em.getTransaction().commit();
em.close();
emf.close();

Read (읽기)

EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
EntityManager em = emf.createEntityManager();

EntityClass entity = em.find(EntityClass.class, id);
// use entity

em.close();
emf.close();

Update (수정)

EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
EntityManager em = emf.createEntityManager();

em.getTransaction().begin();

EntityClass entity = em.find(EntityClass.class, id);
// update entity properties
em.merge(entity);

em.getTransaction().commit();
em.close();
emf.close();

Delete (삭제)

EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
EntityManager em = emf.createEntityManager();

em.getTransaction().begin();

EntityClass entity = em.find(EntityClass.class, id);
em.remove(entity);

em.getTransaction().commit();
em.close();
emf.close();

마무리

이렇게 하여 자바 어플리케이션에서 ORM을 사용하여 데이터베이스의 CRUD 작업을 간편하게 수행할 수 있습니다. ORM을 사용하면 SQL 쿼리 작성을 줄이고 객체 중심의 개발에 집중할 수 있어 개발 생산성을 향상시킬 수 있습니다.

더 많은 정보를 원하시면 Hibernate 공식 문서를 참고해보세요.

다른 문의 사항이 있으시면 언제든지 물어봐 주세요!