【问题标题】:How to use @ElementCollection for Set<Integer> mapping?如何使用 @ElementCollection 进行 Set<Integer> 映射?
【发布时间】:2020-05-09 22:45:48
【问题描述】:

我有 2 张桌子。 report_id是PK。 animals_in_area 没有 PK 密钥。

我需要通过给定的report_idreport_date 检查animal_report 中的animal_id。 这似乎是一个简单的任务,但我能以某种方式描述animal_report 类中的一个字段Set&lt;Integer&gt; adimalIds,映射到请求的区域吗? 我试过@ElementCollection + @CollectionTable,但它会自动将report_id映射到area_id,因为@Id注释。

@ElementCollection
@CollectionTable(name = "animals_in_area", joinColumns = @JoinColumn(name = "area_id"))
@Column(name = "animal_id")
private Set<Integer> adimalIds = new HashSet<>();

我想在 DTO 中使用criteriaBuilder.isMember(animalIdRequest, adimalIds)

什么是经典方式?加入并获得设置?

               animal_report                                 animals_in_area
    ---------------------------------                      -------------------
    report_id | report_date | area_id                      area_id | animal_id  
    ---------------------------------                      -------------------
        1     |  01.01.2020 |  100                           100   |   1001
        2     |  01.01.2020 |  101                           100   |   1002
                                                             100   |   1003
                   .....                                     101   |   1002
                                                             101   |   1004

@Entity
@Table(name = "animal_report")
public class AnimalReport implements Serializable {

  @Id
  @Column(name = "report_id")
  private Long reportId;

  @Column(name = "report_date")
  private LocalDate reportDate;

  @Column(name = "area_id")
  private Integer areaId;
  ...
}

【问题讨论】:

    标签: java hibernate join one-to-many hibernate-onetomany


    【解决方案1】:

    您应该通过以下方式更正您的映射:

    @Entity
    @Table(name = "animal_report")
    public class AnimalReport implements Serializable {
    
      @ElementCollection
      @CollectionTable(name = "animals_in_area", joinColumns = @JoinColumn(name = "area_id", referencedColumnName = "area_id"))
      @Column(name = "animal_id")
      private Set<Integer> animalIds = new HashSet<>();
    
      // ...
    }
    

    您必须使用referencedColumnName,因为animals_in_area.area_id 列引用的不是animal_report 表的主键列。

    【讨论】:

      猜你喜欢
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      相关资源
      最近更新 更多