Programing

JPA에서 복합 기본 키를 만들고 처리하는 방법

lottogame 2020. 8. 14. 08:15
반응형

JPA에서 복합 기본 키를 만들고 처리하는 방법


동일한 데이터 항목의 버전을 갖고 싶습니다. 즉, 항목을 다른 버전 번호로 복제하고 싶습니다.

id - Version 기본 키가됩니다.

엔티티는 어떻게 생겼습니까? 다른 버전으로 복제하려면 어떻게해야합니까?

id Version ColumnA

1   0      Some data
1   1      Some Other data
2   0      Data 2. Entry
2   1      Data

당신은 할 수 있습니다 Embedded class당신이 키를 포함하는, 다음으로 그 클래스에 대한 참조가 EmbeddedId귀하의에서 Entity.

@EmbeddedId@Embeddable주석 이 필요합니다 .

@Entity
public class YourEntity {
    @EmbeddedId
    private MyKey myKey;

    @Column(name = "ColumnA")
    private String columnA;

    /** Your getters and setters **/
}
@Embeddable
public class MyKey implements Serializable {

    @Column(name = "Id", nullable = false)
    private int id;

    @Column(name = "Version", nullable = false)
    private int version;

    /** getters and setters **/
}

이 작업을 달성하는 또 다른 방법은 사용하는 것입니다 @IdClass여러분 모두 주석과 장소를 id한다는 점에서 IdClass. 이제 @Id두 속성 모두에 일반 주석을 사용할 수 있습니다.

@Entity
@IdClass(MyKey.class)
public class YourEntity {
   @Id
   private int id;
   @Id
   private int version;

}

public class MyKey implements Serializable {
   private int id;
   private int version;
}

MyKey 클래스는 Serializable다음을 사용 하는 경우 구현해야합니다.@IdClass


주요 클래스 :

@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {

    public EntryKey() {
    }

    public EntryKey(final Long id, final Long version) {
        this.id = id;
        this.version = version;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getVersion() {
        return this.version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public boolean equals(Object other) {
        if (this == other)
            return true;
        if (!(other instanceof EntryKey))
            return false;
        EntryKey castOther = (EntryKey) other;
        return id.equals(castOther.id) && version.equals(castOther.version);
    }

    public int hashCode() {
        final int prime = 31;
        int hash = 17;
        hash = hash * prime + this.id.hashCode();
        hash = hash * prime + this.version.hashCode();
        return hash;
    }

    @Column (name = "ID")
    private Long id;
    @Column (name = "VERSION")
    private Long operatorId;
}

엔티티 클래스 :

@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {

    @EmbeddedId
    public EntryKey getKey() {
        return this.key;
    }

    public void setKey(EntryKey id) {
        this.id = id;
    }

    ...

    private EntryKey key;
    ...
}

다른 버전과 복제하려면 어떻게해야합니까?

You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.


The MyKey class (@Embeddable) should not have any relationships like @ManyToOne

참고URL : https://stackoverflow.com/questions/13032948/how-to-create-and-handle-composite-primary-key-in-jpa

반응형