웹사이트 검색

JPA 주석 - Hibernate 주석


JPA 주석은 Java 개체를 데이터베이스 테이블, 열 등에 매핑하는 데 사용됩니다. Hibernate는 JPA 사양의 가장 인기 있는 구현이며 몇 가지 추가 주석을 제공합니다. 오늘 우리는 간단한 코드 스니펫과 함께 JPA 주석과 Hibernate 주석을 살펴볼 것입니다.

JPA 주석 - Hibernate 주석

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

Java 객체를 데이터베이스 테이블에 매핑하기 위한 JPA 주석

몇 가지 중요한 JPA 주석을 살펴보겠습니다. 이러한 주석은 javax.persistence 패키지에 있습니다.

  1. javax.persistence.Entity: Specifies that the class is an entity. This annotation can be applied on Class, Interface of Enums.

    import javax.persistence.Entity;
    
    @Entity
    public class Employee implements Serializable {
    }
    
  2. @Table: It specifies the table in the database with which this entity is mapped. In the example below the data will be stores in the “employee” table. Name attribute of @Table annotation is used to specify the table name.

    import javax.persistence.Entity;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "employee")
    public class Employee implements Serializable {
    }
    
  3. @Column: Specify the column mapping using @Column annotation. Name attribute of this annotation is used for specifying the table’s column name.

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "employee")
    public class Employee implements Serializable {
     
      @Column(name = "employee_name")
      private String employeeName;
    }
    
  4. @Id: This annotation specifies the primary key of the entity.

    import javax.persistence.*;
    
    @Entity
    @Table(name = "employee")
    public class Employee implements Serializable { 
      @Id
      @Column(name = "id")
      private int id;
    }
    
  5. @GeneratedValue: This annotation specifies the generation strategies for the values of primary keys.

    import javax.persistence.*;
    
    @Entity
    @Table(name = "employee")
    public class Employee implements Serializable {
      
      @Id
      @Column(name = "id")
      @GeneratedValue(strategy=SEQUENCE, generator="ID_SEQ")
      private int id;
    }
    
  6. @Version: We can control versioning or concurrency using this annotation.

    import javax.persistence.*;
    
    @Entity
    @Table(name = "employee")
    public class Employee implements Serializable {
      @Version
      @Column(name = "version")
      private Date version;
    }
    
  7. @OrderBy: Sort your data using @OrderBy annotation. In example below, it will sort all employees_address by their id in ascending order.

    @OrderBy("id asc")
    private Set employee_address;
    
  8. @Transient: Every non static and non-transient property of an entity is considered persistent, unless you annotate it as @Transient.

     
    @Transient
    Private int employeePhone;
    
  9. @Lob: Large objects are declared with @Lob.

     
    @Lob
    public String getEmployeeAddress() {
        return employeeAddress;
    }
    

위의 주석 세트는 엔티티를 정의하기 위해 가장 일반적으로 사용되는 JPA 주석입니다.

테이블 간 매핑을 위한 Hibernate 주석

다른 테이블과 엔터티 간의 연결 매핑을 지정하는 데 사용되는 또 다른 주석 세트가 있습니다. 아래 언급된 시나리오를 고려하여 예를 들어 보겠습니다.

  • 'employee' 및 'employeeDetail' 테이블은 일대일 연결을 가지며 동일한 기본 키를 공유합니다.
  • 'communication' 및 'communicationDetail' 테이블은 외래 키로 연결됩니다. 또한 일대일 연결입니다.
  • 'communication' 및 'employee' 테이블은 통신이 소유자인 다대일 연결에서 외래 키를 사용하여 연결됩니다.
  • 'employee' 및 'employeeStatus' 테이블은 직원이 소유자인 다대일 연결에서 외래 키를 통해 연결됩니다.

@OneToOne Employee 및 EmployeeDetail 엔터티는 동일한 기본 키를 공유하며 @GeneratedValue를 사용하여 연결할 수 있습니다. Employee의 id 값은 EmployeeDetail의 id에 사용됩니다.

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
   
  @Id
  @Column(name = "id")
  @GeneratedValue
  private int id;
   
  @OneToOne(cascade = CascadeType.MERGE)
  @PrimaryKeyJoinColumn
  private EmployeeDetail employeeDetail;
}
 
@Entity
@Table(name = "employeeDetail")
public class EmployeeDetail implements Serializable {
 
  @Id
  @Column(name = "id")
  private int id;
}

참고 사항:

  • @PrimaryKeyJoinColumn은 동일한 기본 키를 공유하는 관련 항목에 사용해야 합니다.
  • 엔터티 중 하나가 외래 키를 보유하는 경우 @OneToOne은 mappedBy 속성이어야 합니다.

Communication과 CommunicationDetail은 외래 키를 통해 연결되므로 @MapsId가 동일하게 사용됩니다.

@Entity
@Table(name = "communicationDetail")
public class CommunicationDetail implements Serializable {
 
  @Id
  @Column(name = "id")
  @GeneratedValue
  private int id;
   
  @OneToOne
  @MapsId
  @JoinColumn(name = "communicationId")
  private Communication communication;
}
 
@Entity
@Table(name = "communication")
public class Communication implements Serializable {
 
  @Id
  @Column(name = "ID")
  @GeneratedValue
  private Integer id;
 
  @OneToOne(mappedBy = "communication", cascade = CascadeType.ALL)
  private CommunicationDetail communicationDetail;
}

@ManyToOne 많은 직원이 동일한 상태를 공유할 수 있습니다. 따라서 직원 대 직원 상태는 다대일 관계입니다. @ManyToOne 주석은 동일하게 사용할 수 있습니다.

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
 
  @ManyToOne
  @JoinColumn(name = "statusId")
  private EmployeeStatus status;
}

@OneToMany Employee to Communication은 일대다 관계입니다. 이 관계의 소유자는 Communication이므로 Employee의 'mappedBy' 속성을 사용하여 양방향 관계로 만듭니다.

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
 
  @OneToMany(mappedBy = "employee", fetch = FetchType.EAGER)
  @OrderBy("firstName asc")
  private Set communications;
}

@PrimaryKeyJoinColumn 이 주석은 동일한 기본 키를 공유하는 엔티티를 연결하는 데 사용됩니다.

@Entity
@Table(name = "employee")
public class Employee implements Serializable {
   
  @Id
  @Column(name = "id")
  @GeneratedValue
  private int id;
   
  @OneToOne(cascade = CascadeType.MERGE)
  @PrimaryKeyJoinColumn
  private EmployeeDetail employeeDetail;
}

@JoinColumn @JoinColumn 주석은 엔터티 중 하나가 외래 키를 보유할 때 일대일 또는 다대일 연결에 사용됩니다.

@ManyToOne
@JoinColumn(name = "statusId")
private EmployeeStatus status;

@JoinTable: @MapsId 주석.

@OneToOne
@MapsId
@JoinColumn(name = "communicationId")
private Communication communication;

상속 매핑을 위한 Hibernate 주석

이제 Hibernate에서 상속 매핑 주석을 이해하려고 노력합시다. Hibernate는 세 가지 기본 상속 매핑 전략을 지원합니다.

  • 클래스 계층별 테이블
  • 하위 클래스별 테이블
  • 구체 클래스별 테이블

우리는 각 유형에 대한 예를 고려할 것입니다.

  1. Table per class hierarchy - single table per Class Hierarchy Strategy.

    @Entity
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name="cartype", discriminatorType=DiscriminatorType.STRING )
     
    @DiscriminatorValue("Car")
    public class Car {  }
     
    @Entity
    @DiscriminatorValue("BMW")
    public class BMW extends Car {  }
    
  2. Table per class/subclass - joined subclass Strategy.

    @Entity
    @Inheritance(strategy=InheritanceType.JOINED)
    public class Ship implements Serializable {}
     
    @Entity
    @PrimaryKeyJoinColumn
    public class Titanic extends Ship {}
    
  3. Table per concrete class.

    @Entity
    @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    public class Aeroplane implements Serializable {}
    
  4. @DiscriminatorColumn: As the name suggests this column is the descriminator and this annotation specifies the discriminator column for the SINGLE_TABLE and JOINED Inheritance mapping strategies.

    @Entity
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name="cartype", discriminatorType=DiscriminatorType.STRING )
    

이것이 JPA 및 Hibernate 주석의 전부입니다. 참조: Hibernate API 문서