본문 바로가기

백엔드 개발/JPA

[하이버네이트 유저 가이드 파헤치기] 매핑 타입 - 2.1

반응형

2.1 매핑 타입 (Mapping types)

하이버네이트는 애플리케이션 데이터의 자바와 JDBC 표현을 모두 이해한다.

애플리케이션 데이터를 데이터베이스에서 조회하고 입력하는 기능은 하이버네이트 타입의 기능이다.

이런 사용 사례에서 타입은 org.hibernate.type.Type interface의 구현이다.

또한, 이 하이버네이트 타입은 자바 타입의 동등성 확인 방법이나 값 복사와 같은 다양한 행동적 측면을 설명한다.

 

필자 해설
잘 이해가 안 될 수 있는 대목이다.
이후 유저 가이드에서 자세하게 다룰 부분이지만 대략적으로 설명하겠다.
하이버네이트 타입 중 StringType은 JDBC 타입 VARCHAR과 자바 타입 java.lang.String를 연결해준다.
그렇기 때문에 애플리케이션 데이터를 DB에서 조회하고 입력할 수 있는 것이다.
하이버네이트 타입은 JDBC 타입과 자바 타입을 이해하고 있으므로 서로를 전환해줄 수도 있는 것이다.

각 타입의 매핑은 org.hibernate.type.BasicTypeRegistry라고 하는 Hibernate 내부 서비스에 의해 관리된다.

 

원문
Hibernate understands both the Java and JDBC representations of application data. The ability to read/write this data from/to the database is the function of a Hibernate type. A type, in this usage, is an implementation of the org.hibernate.type.Type interface. This Hibernate type also describes various behavioral aspects of the Java type such as how to check for equality, how to clone values, etc.

"타입"이라는 단어의 사용 예

하이버네이트 타입은 Java 타입도 SQL 데이터 타입도 아니다. 하이버네이트 타입은 자바 타입과 SQL 타입을 매핑하는 정보뿐만 아니라 주어진 자바 타입을 관계형 데이터베이스에 저장하는 방법과 가져오는 방법에 관한 정보를 제공한다.

하이버네이트에 관한 논의에서 "타입"이라는 용어를 보게 된다면 문맥에 따라 각각 자바 타입, JDBC 타입, 하이버네이트 타입을 뜻할 수 있다는 것에 유의하자.

 

원문
The Hibernate type is neither a Java type nor a SQL data type. It provides information about mapping a Java type to an SQL type as well as how to persist and fetch a given Java type to and from a relational database.
When you encounter the term type in discussions of Hibernate, it may refer to the Java type, the JDBC type, or the Hibernate type, depending on the context.

 


타입의 유형에 이해를 돕기 위하여, 우리가 연결하기를 원하는 간단한 테이블과 도메인 모델을 보도록 하자.

(To help understand the type categorizations, let’s look at a simple table and domain model that we wish to map.)

 

Example 1. A simple table and domain model

create table Contact (
    id integer not null,
    first varchar(255),
    last varchar(255),
    middle varchar(255),
    notes varchar(255),
    starred boolean not null,
    website varchar(255),
    primary key (id)
)
@Entity(name = "Contact")
public static class Contact {

	@Id
	private Integer id;

	private Name name;

	private String notes;

	private URL website;

	private boolean starred;

	//Getters and setters are omitted for brevity
}

@Embeddable
public class Name {

	private String firstName;

	private String middleName;

	private String lastName;

	// getters and setters omitted
}

 

큰 관점에서, 하이버네이트 타입 유형은 두 가지 그룹이 있다.

  • Value types
  • Entity types

 

2.1.1 Value types

밸류 타입(value type)은 자신의 라이프 사이클을 규정하지 않는 데이터의 조각이다.

밸류 타입은 사실상 엔터티(Entity)가 소유한다. 이는 엔티티가 밸류 타입의 라이프 사이클을 규정하기 때문이다.

다른 방식으로 보자면, 엔티티의 모든 상태는 전적으로 밸류 타입에 의해 구성된다.

이 엔티티의 상태를 나타내는 필드 혹은 자바의 속성은 영속적인 속성(persistent attributes)이라는 용어로 정의된다.

이러한 위 예시의 Contact 클래스의 영속적인 속성은 밸류 타입이다.

 

필자 해설

영속적인 속성(persistent attributes)

예시를 보면 Conact 클래스의 starred 필드와 Contact 테이블의 starred 칼럼이 타입명(boolean)과 이름이 일치한다.
Contact 클래스의 인스턴스를 생성해서 EntityManager를 통해 영속화하면 Contact 인스턴스의 starred 필드(혹은 속성)가 Contact 테이블의 starred 칼럼으로 저장된다.
starred 필드는 DB에 저장되어서 지속적으로 DB를 통해 정보를 조회/수정을 할 수 있다.
그러므로, 밸류 타입은 영속적인 속성이 되는 것이다.

 

밸류 타입은 세 가지 하위 유형으로 더 상세히 구분된다.

 

Basic types

Contact 클래스에서 name 필드를 제외하고 Contact 테이블과 매핑이 되는 모든 속성이 베이식 타입이다. 

베이식 타입에 관한 상세한 논의는 이후에 별도 챕터가 마련되어 있다.

 

Embeddable types

위 예제의 Contact 클래스에 name 필드가 임베디드 타입이다. 이 또한 상세한 논의는 별도 챕터가 마련되어 있다.

 

Collection types

비록 앞서 말한 예시에는 없는 기능이지만, 컬렉션 타입 역시 밸류 타입 중에서 구분되는 유형이다.

상세한 논의는 별도 챕터가 마련되어 있다.

 

원문

A value type is a piece of data that does not define its own lifecycle. It is, in effect, owned by an entity, which defines its lifecycle.
Looked at another way, all the state of an entity is made up entirely of value types. These state fields or JavaBean properties are termed persistent attributes. The persistent attributes of the Contact class are value types.
Value types are further classified into three sub-categories:

Basic typesin
mapping the Contact table, all attributes except for name would be basic types. Basic types are discussed in detail in Basic types

Embeddable types
the name attribute is an example of an embeddable type, which is discussed in details in Embeddable types

Collection types
although not featured in the aforementioned example, collection types are also a distinct category among value types. Collection types are further discussed in Collections

 

2.1.2 Entity types

유일한 식별자를 가지기 때문에 엔티티는 다른 오브젝트와 독립적으로 존재한다.

반면에 엔티티 타입에 값은 독립적으로 존재하지 않는다. (종속적이다.)

엔티티는 유일한 식별자를 사용하여 데이터베이스 테이블의 로우와 상관 관계가 있는 도메인 모델 클래스이다.

유일한 식별자가 필수이기 때문에, 엔티티는 독립적으로 존재하고, 자신의 라이프 사이클을 규정한다.

위 예시의 Contact 클래스 그 자체가 엔티티의 예시이다.

 

필자 해설
엔티티의 유일한 식별자는 연결된 테이블의 기본키과 연동된다.

 

원문
Entities, by nature of their unique identifier, exist independently of other objects whereas values do not. Entities are domain model classes which correlate to rows in a database table, using a unique identifier. Because of the requirement for a unique identifier, entities exist independently and define their own lifecycle. The Contact class itself would be an example of an entity.

 

원문 링크

 

 

반응형