직렬화란?
(1) 데이터 구조나 오브젝트 상태를 동일하거나 다른 컴퓨터 환경에 저장(이를테면 파일이나 메모리 버퍼에서, 또는 네트워크 연결 링크간 전송) 하고 나중에 재구성 할 수 있는 포맷으로 변환하는 과정이다. 오브젝트를 직렬화 하는 과정의 반대로, 일련의 바이트로부터 데이터 구조를 추출하는 일은 역직렬화라고 한다.
위키 백과 - https://ko.wikipedia.org/wiki/%EC%A7%81%EB%A0%AC%ED%99%94
(2) 시스템적으로 이야기 하자면 JVM(Java Virtual Machin 이하 JVM) 의 메모리 상주(힙 또는 스택)되어 있는 객체 데이터를 바이트 형태로 변환하는 기술과 직렬화된 바이트 형태의 데이터를 객체로 변환해서 JVM 으로 상주 시키는 형태를 같이 이야기 한다.
우아한 형제들 기술 블로그 - https://techblog.woowahan.com/2550/
(3) 직렬화란 객체를 데이터 스트림으로 만드는 것을 뜻한다. 다시 얘기하면 객체에 저장된 데이터를 스트림에 쓰기(Write) 위해 연속적인 데이터로 변환하는 것을 말한다. 반대로 스트림으로부터 데이터를 읽어서 객체를 만드는 것을 역직렬화 라고 한다.
직렬화를 사용함으로
- 어플리케이션에서 데이터를 저장하고 검색하면서 영속성을 보장 할 수 있다.
- 입력 및 출력 스트림이 소켓으로 사용되는 경우 우리는 다른 프로그램들과의 네트워크 통신이 가능하다.
- JAVA/RMI 원격 메서드 호출을 구현하기 위해 직렬화를 사용한다.
[ https://docs.oracle.com/javase/8/docs/platform/rmi/spec/rmi-protocol4.html ]
- 데이터베이스에 저장될 수 있다.
ObjectInputStream, ObjectOutputStream
ObjectInputStream : 직렬화 (InputStream 상속) - ObjectInputStream 클래스 API
ObjectOutputStream : 역직렬화 (outputStream 상속) - ObjectOutputStream 클래스 API
둘다 기반 스트림을 필요로 하는 보조 스트림이다. 만일 파일 객체를 저장하고 싶으면 다음과 같이 한다.
[전체 예제]
import java.io.*;
class Test implements Serializable{
String name="Hong";
transient String id="1";
int age= 20;
}
class Serialize{
public static void main(String args[]) throws Exception{
// Createing the serializable data
Test t1=new Test();
// Opening an output stream
FileOutputStream fos= new FileOutputStream("Myfile.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
// writing the serialized data
oos.writeObject(t1); // object is serialized here
// Closing the output stream
oos.close()
/* Later on
we can deserialize
the object
*/
FileInputStream fis=new FileInputStream("Myfile.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Test t2=(Test)ois.readObject(); // Object is deserialized here
System.out.println(t2.id+":::::"+ t2.name+":::::"+ t2.age);
}
}
- 위의 Test.class 를 직렬화 가능한 클래스로 사용하기 위해서는 Serializable 인터페이스를 상속 받아야한다.
(안할시 오류가 발생한다. )
Serializable 인터페이스의 특징
1) 빈 클래스이다
직렬화할 클래스라는 것을 알려주기 위한 마커 목적으로 생성된 클래스이기 때문이다.
public interface Serializable {
}
2) 상속 유형에 다라 직렬화할 수 있는 범위가 달라진다.
public class SuperUserInfo implements Serializable {
String name;
String password;
}
public class UserInfo extends SuperUserInfo {
int age
}
- 조상 클래스인 SuperUserInfo 가 Serializable 을 구현 하였으므로 UserInfo 역시 직렬화가 가능하다.
Public class SuperUserInfo {
String name;
String passowrd;
}
Public class UserInfo extends SuperUserInfo implements Serializable {
Int age;
}
- 하위 클래스인 UserInfo 만 Serializable 을 구현 하였으므로 SuperUserInfo 의 객체는 직렬화가 되지 않는다.
3) Primitive 타입의 객체는 Serializable 을 기본으로 구현한다.
4) Object.class 는 Serializable 을 구현하지 않는다. 만약 했더라면 모든 객체가 Serialization 이 가능 했을 것이다. Object 는 모든 객체의 최고 조상이기 때문이다.
public class Object {
....
}
5. Serializable 이 불가능한 객체를 담을 경우에는 다음과 같은 에러가 난다. 이 경우 표시를 해줘야 한다.
“RuntimeException: Exception in thread “main” java.io.NotSerializableException: java.io.ObjectOuputStream.”
6. transient 키워드를 통해서 직렬화 대상에서 객체를 제외 시킬 수 있다.
import java.io.* ;
public class test implements Serializable
{
…
transient Sting name ;
…
}
6. SerialVersionUID 가 존재한다. 버전 관리를 목적으로 둔다.
public class test implements Serializable {
private static final long serialVersionUID = 1L;
...
7. 아래 직렬화의 종류와 사용 이유에 대해 잘 정리가 되어있다.
https://techblog.woowahan.com/2550/
자바 직렬화, 그것이 알고싶다. 훑어보기편 | 우아한형제들 기술블로그
{{item.name}} 자바의 직렬화 기술에 대한 대한 이야기입니다. 간단한 질문과 답변 형태로 자바 직렬화에 대한 간단한 설명과 직접 프로젝트를 진행하면서 겪은 경험에 대해 이야기해보려 합니다.
techblog.woowahan.com
JPA 의 Serialization 과 Persistence
우리는 이전에 데이터의 영속성 관리를 위해 Serialization 을 이용한다 했는데
Java 에서 제공하는 JPA(Java Persistence API) 를 예로 들 수 있다.
JPA 는 JavaBeans(EJB 3.0) 에 표준화된 기술로
Java Persistence 는 엔티티 모델을 단순화하여 객체를 관계형 데이터 베이스에 저장하는 API 를 제공한다.
하이버네이트에서는 모든 엔티티에 Serializable 인터페이스를 구현하도록 권장되어있다.
@Entity
public class Student implements Serializable
{
@id
@column(name=“id” table=“Strudent”)
private int number ; // primary key
@column(name=“first_name” table=“Strudent”)
private String first_name ;
@column(name=“last_name” table=“Strudent”)
private String last_name ;
}
또한 지속적인 엔티티 상태를 제공해 주는데 이러한 영속성 객체 대한 관리를 EntityManager 가 해준다.
EntityManagerFactory emf = Persistence.createEntityManagerFactory(“StudentDB”) ;
EntityManager em = emf.createEntityManager() ;
EntityTransaction et = em.getTransaction() ;
et.begin() ;
Student s = new Student(12345,”Elton”,”John”) ;
em.persist(s) ;
et.commit() ;
em.close() ;
emf.close() ;
영속성을 이용해서 데이터를 조회하기도 한다.
EntityManagerFactory emf
= Persistence.createEntityManagerFactory(“StudentDB”) ;
EntityManager em = emf.createEntityManager() ;
// find by primary key, null if not found
Student s = em.find(Student.class,12345) ;
em.close() ;
emf.close() ;
이해를 돕기 위해 JPA 의 Persistence Context 구조를 참고한다.
https://victorydntmd.tistory.com/207
[Spring JPA] 영속 환경 ( Persistence Context )
영속성 컨텍스트 ( Persistence Context ) persistence context는 엔티티를 영구 저장하는 환경으로, 논리적인 개념입니다. 엔티티 매니저( Entity Manager )로 엔티티를 저장( persist() ) , 조회( find() 또는 J..
victorydntmd.tistory.com
Serializable 에 대해 생각해 볼만한 질문들 :
1)
https://www.inflearn.com/questions/17117
Serializable 질문 드립니다 - 인프런 | 질문 & 답변
강의를 역시나 재미나게 보고 있습니다 ㅎㅎ 가끔 블로그를 보면 entity에 Serializable을 붙이는 경우가 있는데 이것에 대한 설명 부탁드립니다. 제가 아는 한에서 Serializable은 객체를 다른 서버로(ip
www.inflearn.com
Delete field from old java class implementing Serializable
Suppose i have version of class MyClass where i have two fields int count and String name. And i have persisted the byte stream to file. After i delete the attribute name from the class then also ...
stackoverflow.com
출처 :
https://www.infoworld.com/article/2072752/the-java-serialization-algorithm-revealed.html
https://www.infoworld.com/article/2073641/lightweight-persistence-with-java-serialization.html
https://howtodoinjava.com/java/serialization/java-serialization/
https://perso.telecom-paristech.fr/bellot/POOP5/3a.Persistence_and_serialization.pdf
https://techblog.woowahan.com/2550/
https://sas-study.tistory.com/345
'java' 카테고리의 다른 글
[JAVA] 람다식 실용예제 - 실행 어라운드 패턴 (0) | 2021.12.24 |
---|---|
디자인 패턴(Design Pattern) - 목적에 따른 분류 (0) | 2021.11.26 |
[JAVA] 자바의 정석 - Stream (0) | 2021.10.31 |
[JAVA] JVM 에 대하여 ( + Garbage Collection) (0) | 2021.10.29 |
[JAVA] 자바의 정석 - Execption 정리 (0) | 2021.10.21 |