source

주석 @Id 및 @GeneratedValue(전략 = GenerationType)의 용도는 무엇입니까?아이덴티티)왜 세대형은 아이덴티티인가?

goodcode 2022. 9. 21. 00:00
반응형

주석 @Id 및 @GeneratedValue(전략 = GenerationType)의 용도는 무엇입니까?아이덴티티)왜 세대형은 아이덴티티인가?

@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)

이 주석을 사용하는 이유는 무엇입니까?테이블 ID 값이 자동으로 증가하는지 확인해야 합니다(Generation Type).ID) 이 주석을 사용할 때 실제로 발생하는 다른 유형의 작업이 있습니까?

public class Author extends Domain
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id") 
    private Integer id;

    @Basic(optional = false)
    @Column(name = "name") 
    private String name;

    @Column(name = "address") 
    private String address; 

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "authorId")
    private List<Book>
    bookList;

    public Author()
    { 
        setServiceClassName("wawo.tutorial.service.admin.AuthorService");
    }
}

* Domain Abstract 클래스를 확장해야 합니까?무슨 소용이에요?

우선, 주석을 설정 방법으로 사용하는 것은 끝없는 XML 설정 파일에 대처하는 대신 편리한 방법입니다.

@Id로부터 물려받은 것입니다.javax.persistence.Id② 아래 멤버필드가 현재 엔티티의 프라이머리 키임을 나타냅니다.및 및 할 수 .reflect는 이 주석을 기반으로 작동합니다.자세한 내용은 javadoc에서 ID를 확인하십시오.

@GeneratedValue주석은 지정된 열(필드)의 증가 방법을 구성하는 것입니다.를 들어 " " "를 사용하는 Mysql 라고 지정할 수 .auto_increment표의 정의에서 자기 증분으로 만들고, 그 다음 사용합니다.

@GeneratedValue(strategy = GenerationType.IDENTITY)

이 데이터베이스 서버 측 전략의 사용도 승인했음을 나타냅니다.또한 이 주석의 값을 다른 요구 사항에 맞게 변경할 수도 있습니다.

1. 데이터베이스에서의 시퀀스 정의

들어 은 "Oracle"을 사용해야 합니다.sequence신탁을 받다

create sequence oracle_seq;

2. 데이터베이스 시퀀스 참조

이제 데이터베이스에 시퀀스가 있지만 다음 명령을 사용하여 Java와 DB 간의 관계를 설정해야 합니다.

@SequenceGenerator(name="seq",sequenceName="oracle_seq")

sequenceName의 의 실제 입니다.name자바에서는 그렇게 부르고 싶은 것입니다. 하다를 지정해야 합니다.를 지정해야 .sequenceNamename의 경우는, 「 」 「 」 「 」 「 」를 사용합니다.namesequenceName간간을시

3. Java에서의 시퀀스 사용

마지막으로 자바에서 이 시퀀스를 사용할 때입니다.추가:

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")

generator필드는 사용할 시퀀스 생성기를 나타냅니다. DB에서 입니다.nameSequenceGenerator.

4. 완료

따라서 전체 버전은 다음과 같습니다.

public class MyTable
{
    @Id
    @SequenceGenerator(name="seq",sequenceName="oracle_seq")        
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")               
    private Integer pid;
}

이제 이러한 주석을 사용하여 JavaWeb을 쉽게 개발할 수 있습니다.

오브젝트 릴레이셔널 맵핑콘텍스트에서는 모든 오브젝트에 일의의 식별자가 필요합니다.주석을 사용하여 도면요소의 기본 키를 지정합니다.

주석은 기본 키를 생성하는 방법을 지정하는 데 사용됩니다.이 예에서는 다음과 같은 전략을 사용하고 있습니다.

지속성 공급자가 데이터베이스 ID 열을 사용하여 엔티티에 기본 키를 할당해야 함을 나타냅니다.

다른 전략이 있습니다. 자세한 내용은 여기를 참조하십시오.

Simply, @Id: This annotation specifies the primary key of the entity. 

@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used. 

GenerationType enum defines four strategies: 
1. Generation Type . TABLE, 
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY   
4. Generation Type. AUTO

GenerationType.SEQUENCE

With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities. 

GenerationType.TABLE

With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities. 

GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.

GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used. 

참고 자료: - https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html

이 주석을 사용하는 이유는 무엇입니까?

  • 먼저 모든 사람에게 다음과 같은 주석을 상기시키고 싶습니다.@Id는, 퍼시스텐스 레이어에 메타데이터를 제공하고 있습니다(휴면 상태라고 가정합니다).이 메타데이터는 대부분 .class 파일에 저장되며(데이터베이스에는 저장되지 않음), 엔티티를 인식, 해석 및 관리하는 방법을 휴지 상태로 만들기 위해 사용됩니다.그럼 왜 주석을 사용하는 거죠?지속성 계층에 엔티티 관리 방법에 대한 적절한 정보를 제공합니다.

@Id 주석을 사용하는 이유는 무엇입니까?

  • @Id주석은 JPA를 사용하여 도면요소를 작성할 때 필요한 두 가지 필수 주석 중 하나입니다.다른 하나는@Entity.@Id는, 다음의 2가지를 실현합니다.

    1) 데이터베이스 테이블에 매핑되었을 때 이 필드가 이 클래스의 고유 식별자가 되는 것을 나타냅니다.

    2) 의 존재@Id지속성 계층은 이 클래스 내의 다른 모든 필드가 데이터베이스 행에 매핑됨을 알립니다.

@GeneratedValue를 사용하는 이유

  • 를 표시함으로써@Id와 함께 출전하다.@GeneratedValue이 시점에서,id generation즉, 퍼시스텐스레이어가 우리를 위한 ID 값을 생성하고 자동 증가를 처리합니다.어플리케이션에서는 다음 4세대 전략 중 하나를 선택할 수 있습니다.

    1) 자동

    2) 표

    3) 시퀀스

    4) 아이덴티티

  • 전략이 지정되지 않은 경우 AUTO로 간주됩니다.

전략 = GenerationType이란?아이덴티티가 실제로 하는 일?

  • 세대 전략을 다음과 같이 지정할 때GenerationType.IDENTITYpersistence provider(certificate)에게 ID의 자동 증분을 데이터베이스가 처리하도록 지시하고 있습니다.postgres를 기본 데이터베이스로 사용하고 전략을 다음과 같이 지정하는 경우:IDENTITY같이
create table users (
       id  bigserial not null,
        primary key (id)
    )

  • 은 아이디이다, 입니다.bigserial, 빅시리얼이란?포스트그레스 문서에 따르면bigserial is a large autoincrementing integer.

결론

  • 지정:
@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

  • 기본 지속성 계층에 id 필드를 데이터베이스 내의 고유 식별자로 사용하도록 지시했습니다., 지속 , 「」, 「」, 「」, 「」의 ID 의 했습니다.GenerationType.IDENTITY.

언급URL : https://stackoverflow.com/questions/20603638/what-is-the-use-of-annotations-id-and-generatedvaluestrategy-generationtype

반응형