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

时间:2019-02-20 03:35:09

标签: java spring-boot jpa

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

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

Database Schema

因此,当我尝试使用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错误。

所以我在自己的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;
    }
}

对于解决此错误消息的任何指导表示赞赏。 谢谢!

1 个答案:

答案 0 :(得分:0)

对于标签表,您不需要实体类。它在“历史”实体中的耐用性如下:

  @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