programing

Embeddable과 EmbeddedId 사이의 JPA 매핑 @ManyToOne

elseif 2023. 3. 10. 21:14

Embeddable과 EmbeddedId 사이의 JPA 매핑 @ManyToOne

Spring Boot JPA 어플리케이션에 다음과 같은 설정이 있습니다.

삽입 가능

@Embeddable
public class LogSearchHistoryAttrPK {
    @Column(name = "SEARCH_HISTORY_ID")
    private Integer searchHistoryId;

    @Column(name = "ATTR", length = 50)
    private String attr;

    @ManyToOne
    @JoinColumn(name = "ID")
    private LogSearchHistory logSearchHistory;
    ...
}

Embedded Id

@Repository
@Transactional
@Entity
@Table(name = "LOG_SEARCH_HISTORY_ATTR")
public class LogSearchHistoryAttr implements Serializable {
    @EmbeddedId
    private LogSearchHistoryAttrPK primaryKey;

    @Column(name = "VALUE", length = 100)
    private String value;
    ...
}

일대다

@Repository
@Transactional
@Entity
@Table(name = "LOG_SEARCH_HISTORY")
public class LogSearchHistory implements Serializable {
    @Id
    @Column(name = "ID", unique = true, nullable = false)
    private Integer id;

    @OneToMany(mappedBy = "logSearchHistory", fetch = FetchType.EAGER)
    private List<LogSearchHistoryAttr> logSearchHistoryAttrs;
    ...
}

데이터베이스 DDL

CREATE TABLE log_search_history (
    id serial NOT NULL,
    ...
    CONSTRAINT log_search_history_pk PRIMARY KEY (id)
 );

CREATE TABLE log_search_history_attr (
    search_history_id INTEGER NOT NULL,
    attr CHARACTER VARYING(50) NOT NULL,
    value CHARACTER VARYING(100),
    CONSTRAINT log_search_history_attr_pk PRIMARY KEY (search_history_id, attr),
    CONSTRAINT log_search_history_attr_fk1 FOREIGN KEY (search_history_id) REFERENCES
        log_search_history (id)
);

애플리케이션을 기동하면, 다음의 에러가 표시됩니다.

원인: org.hibernate.주석예외: mapped알 수 없는 대상 엔티티 속성: com.foobar.entity를 참조합니다.LogSearchHistoryAttr.logSearchHistory in com.foobar.foobar.discloss.LogSearchHistory.logSearchHistoryAttrs

이 에러가 발생하는 이유를 알 수 없습니다.매핑이 올바른 것 같습니다.제가 가지고 있는 이 지도에 무슨 문제가 있나요?감사합니다!

이동했습니다.mappedBy삽입 가능한 기본 키로 속성을 지정하기 때문에 필드 이름이 더 이상 지정되지 않습니다.logSearchHistory오히려primaryKey.logSearchHistory. 엔트리로 맵을 변경합니다.

@OneToMany(mappedBy = "primaryKey.logSearchHistory", fetch = FetchType.EAGER)
private List<LogSearchHistoryAttr> logSearchHistoryAttrs;

참조: JPA / Hibernate One To Many Mapping (복합 프라이머리 키를 사용)

프라이머리 키 클래스도 만들어야 합니다.LogSearchHistoryAttrPK시리얼 가능한

OneToMany 부품:

@OneToMany(mappedBy = "primaryKey.logSearchHistory", fetch = FetchType.EAGER)
private List<LogSearchHistoryAttr> logSearchHistoryAttrs;

언급URL : https://stackoverflow.com/questions/36084173/jpa-mapping-manytoone-between-embeddable-and-embeddedid