영속성(Persistence)은 데이터를 영구적으로 저장할 수 있는 특성을 의미하며, 데이터가 휘발성 메모리가 아닌 비휘발성 저장소(예: 데이터베이스, 파일 시스템)에 저장되어 프로그램이 종료되거나 시스템이 재부팅되더라도 유지되는 것을 말합니다.
파일 시스템
데이터를 파일로 저장하고 읽어오는 방식.
import java.io.*;
public class FilePersistenceExample {
public static void main(String[] args) throws IOException {
String data = "Persistent data example.";
try (FileWriter writer = new FileWriter("data.txt")) {
writer.write(data);
}
}
}
데이터베이스
관계형 데이터베이스(RDB), NoSQL 데이터베이스 등에 데이터를 저장.
import java.sql.*;
public class DatabasePersistenceExample {
public static void main(String[] args) throws Exception {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
String sql = "INSERT INTO data_table (content) VALUES (?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, "Persistent data example");
stmt.executeUpdate();
}
}
}
Object-Relational Mapping(ORM)
데이터베이스 테이블과 객체를 매핑하여 객체 지향 방식으로 데이터 관리.
import jakarta.persistence.*;
@Entity
public class DataEntity {
@Id @GeneratedValue
private Long id;
private String content;
public DataEntity(String content) {
this.content = content;
}
}
public class JpaPersistenceExample {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("example-unit");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(new DataEntity("Persistent data example"));
em.getTransaction().commit();
em.close();
emf.close();
}
}
상태 | 설명 |
---|---|
비영속(new) | 영속성 컨텍스트와 관계없는 상태로, 데이터베이스와 연결되지 않음. |
영속(managed) | 영속성 컨텍스트에 의해 관리되는 상태. 변경 시 자동으로 데이터베이스에 반영. |
준영속(detached) | 영속성 컨텍스트에서 분리된 상태. 데이터베이스와 동기화되지 않음. |
삭제(removed) | 삭제 상태로, 데이터베이스에서 삭제될 예정. |
영속성은 데이터의 보존과 관리를 위한 필수 개념으로, 파일, 데이터베이스, ORM 등 다양한 방식으로 구현할 수 있습니다.
JPA와 같은 프레임워크는 영속성을 쉽게 관리할 수 있도록 도와주며, 특히 대규모 애플리케이션에서 데이터 관리의 효율성을 극대화합니다.
추가 학습 자료