DAO
는 Data Access Object의 약자로, 데이터베이스나 다른 데이터 저장소에 접근하는 객체를 말합니다. DAO는 주로 데이터베이스와의 통신을 담당하고, 비즈니스 로직과 데이터베이스 간의 결합도를 낮추는 데 사용된다.
일반적으로 DAO
는 데이터베이스와 직접적으로 통신하여 데이터를 조작하는 객체로 사용된다. 하지만 최근에는 ORM(Object-Relational Mapping) 기술이 발전하면서 DAO 패턴의 사용빈도가 줄어들고 있는 추세다 ORM은 객체와 데이터베이스 간의 매핑을 자동으로 처리하여 개발자가 직접 SQL 쿼리를 작성하지 않고도 객체를 통해 데이터베이스에 접근할 수 있도록 도와준다.
ORM(Object-Relational Mapping)은 객체와 관계형 데이터베이스 간의 데이터를 변환하고 매핑하는 프로그래밍 기술 또는 도구이다. ORM은 객체 지향 프로그래밍 언어에서 사용되는 객체와 관계형 데이터베이스에서 사용되는 테이블 간의 불일치를 해결하기 위해 사용된다.
import javax.persistence.*;
@Entity
@Table(name = "Student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private int age;
// Getter 및 Setter 메서드
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = null;
EntityManager entityManager = null;
EntityTransaction transaction = null;
try {
// EntityManagerFactory 생성
entityManagerFactory = Persistence.createEntityManagerFactory("MyPersistenceUnit");
// EntityManager 생성
entityManager = entityManagerFactory.createEntityManager();
// 트랜잭션 시작
transaction = entityManager.getTransaction();
transaction.begin();
// 새로운 학생 객체 생성
Student student = new Student();
student.setName("John");
student.setAge(20);
// 학생 객체 저장 (데이터베이스에 INSERT)
entityManager.persist(student);
// 트랜잭션 커밋
transaction.commit();
} catch (Exception e) {
// 트랜잭션 롤백
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
// EntityManager 종료
if (entityManager != null) {
entityManager.close();
}
// EntityManagerFactory 종료
if (entityManagerFactory != null) {
entityManagerFactory.close();
}
}
}
}
JPA
를 사용하여 MySQL 데이터베이스와 연동하고 새로운 학생 객체를 데이터베이스에 저장한다. JPA는 EntityManager를 통해 데이터베이스와 상호작용하며, EntityManagerFactory를 사용하여 EntityManager를 생성합니다. 개발자는 객체 지향적으로 데이터베이스와 상호작용할 수 있으며, SQL 쿼리를 직접 작성할 필요가 없다.
DAO(Data Access Object)와 ORM(Object-Relational Mapping)은 데이터베이스와의 상호 작용을 돕는 데 사용되는 두 가지 다른 접근 방식이다.
DAO
는 데이터베이스와의 상호 작용을 추상화하는 디자인 패턴이며, ORM
은 객체와 관계형 데이터베이스 간의 매핑을 자동화하는 기술이다. DAO는 데이터베이스에 직접 SQL 쿼리를 작성하여 접근하고 결과를 처리하는 반면, ORM은 객체를 데이터베이스 레코드로 매핑하고 SQL 쿼리를 자동으로 생성하여 데이터베이스와 상호 작용한다.