설명
데이터베이스에 클래스 계층 구조를 저장하는 또 다른 전략은 Joined Table입니다. 이에 대한 특별한 주석이 있습니다.
@Inheritance(strategy = InheritanceType.JOINED)
우리 수업의 예:
@Inheritance(strategy = InheritanceType.JOINED)
@Entity
class User {
int id;
String name;
LocalDate birthday;
}
@Entity
class Employee extends User {
String occupation;
int salary;
LocalDate join;
}
@Entity
class Client extends User {
String address;
}
이 주석을 사용할 때 Hibernate는 각 클래스 및 해당 하위 클래스에 대해 데이터베이스에서 별도의 테이블을 예상합니다. 데이터를 선택할 때 SQL JOIN 연산자를 사용해야 합니다.
데이터베이스 스키마 예:
CREATE TABLE user {
id INT,
name VARCHAR,
birthday DATE
}
CREATE TABLE employee {
id INT,
occupation VARCHAR,
salary INT,
join DATE
}
CREATE TABLE client {
id INT,
address VARCHAR
}
테이블에서 일부 클라이언트의 데이터를 가져오기로 결정한 경우 Hibernate는 테이블을 조인하기 위해 JOIN을 사용해야 합니다.
SELECT u.id, u.name, u.birthday, c.address FROM user u JOIN client c ON u.id = c.id;
@PrimaryKeyJoinColumn
자식 엔터티 클래스에는 부모 엔터티 클래스의 개체 ID를 참조하는 테이블의 열이 있습니다. 이 열의 이름은 기본적으로 상위 클래스의 열 이름과 같습니다.
예:
@Inheritance(strategy = InheritanceType.JOINED)
@Entity
class User {
@Id
int user_identifier;
String name;
LocalDate birthday;
}
@Entity
class Employee extends User {
String occupation;
int salary;
LocalDate join;
}
@Entity
class Client extends User {
String address;
}
그러면 데이터베이스 테이블이 다음과 같이 표시됩니다.
CREATE TABLE user {
user_identifier INT,
name VARCHAR,
birthday DATE
}
CREATE TABLE employee {
user_identifier INT,
occupation VARCHAR,
salary INT,
join DATE
}
CREATE TABLE client {
user_identifier INT,
address VARCHAR
}
종속 테이블의 열 이름을 재정의하려면 @PrimaryKeyJoinColumn 주석을 사용해야 합니다 . 예:
@Inheritance(strategy = InheritanceType.JOINED)
@Entity
class User {
@Id
int user_identifier;
String name;
LocalDate birthday;
}
@Entity
@PrimaryKeyJoinColumn(name=”user_id”)
class Employee extends User {
String occupation;
int salary;
LocalDate join;
}
@Entity
@PrimaryKeyJoinColumn(name=”user_id2”)
class Client extends User {
String address;
}
그러면 데이터베이스 테이블이 다음과 같이 표시됩니다.
CREATE TABLE user {
user_identifier INT,
name VARCHAR,
birthday DATE
}
CREATE TABLE employee {
user_id INT,
occupation VARCHAR,
salary INT,
join DATE
}
CREATE TABLE client {
user_id2 INT,
address VARCHAR
}