繁体   English   中英

JPA 问题,使用父实体的主键作为子实体的主键

[英]JPA Problem, Using Parent Entity's Primary Key for Child's Entity's Primary Key

我目前正在使用 JPA 在 Spring 下开发我的项目。

首先,这是我用于背景信息的数据库架构

数据库架构

因此,当我尝试使用 HISTORY 的 history_id 作为 TAG 的主键时,我遇到了困难。 它给了我...Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: This class [class com.wrapsody.demo.HistoryTag] does not define an IdClass ...Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: This class [class com.wrapsody.demo.HistoryTag] does not define an IdClass错误。

所以我在 HistoryTag.java 中添加了@IdClass(HistoryTag.HistoryTagAssignId.class)

 @NoArgsConstructor(access = AccessLevel.PROTECTED)  @Data @Entity
 @IdClass(HistoryTag.HistoryTagAssignId.class)  
 public class HistoryTag implements Serializable {
     @Id
     @ManyToOne
     private History history;

     @Column
     private String tagName;

     @Builder
     public HistoryTag(String tagName) {
         this.tagName = tagName;
     }

     @NoArgsConstructor
     public static class HistoryTagAssignId implements Serializable {
         private History history;

         public HistoryTagAssignId(History history) {
             this.history = history;
         }
     } 
}

作为参考,这是 History.java

@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Data
@Entity
public class History {
    @Id
    @GeneratedValue
    private Long historyId;

    @Column
    private String historyMaterName;

    @Column
    private String historyFreeSetName;

    History(String historyMaterName, String historyFreeSetName) {
        this.historyMaterName = historyMaterName;
        this.historyFreeSetName = historyFreeSetName;
    }
}

感谢任何解决此错误消息的指导。 谢谢!

对于标签表,您不需要实体类。 它在历史实体中具有双重性:

  @ElementCollection
  @CollectionTable(
        name="TAG",
        joinColumns=@JoinColumn(name="HISTORY_ID")
  )
  @Column(name="TAG_NAME")   
  List<String> tags;

https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection#Basic_Collections

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM