香港专业教育学院添加了2个休眠模型对象
第一桌

      @Entity
      @Table(name = "ACTIVITIES")
     public class ActivityMO extends ModelBase {

        @Column(name = "CA_ID", nullable = false, insertable = true,updatable = true, length = 22, precision = 0)
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO, generator = "G1")
        @SequenceGenerator(name = "G1", sequenceName = "CSM_ACTIVITIES_SEQ")
        private Long id;

        @OneToMany(fetch = FetchType.LAZY, mappedBy = "activityId", cascade = {CascadeType.ALL})
        @Fetch(FetchMode.JOIN)
        List<ActivitiesProductsMO> relatedProducts;

    ...getters / setters
        }


另一个表是

@Entity
@Table(name = "ACTIVITIES_PRODUCTS")
public class ActivitiesProductsMO {

@Column(name = "CAP_ID")
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "G1")
@SequenceGenerator(name = "G1", sequenceName = "ACTIVITIES_PRODUCTS_SEQ")
private Long id;
    @Column(name = "CAP_ACTIVITY_ID")
    private Long activityId;

@Column(name = "CAP_PRODUCT_ID")
private Long productId;

...getters/setters
    }


关键是要用ActivityMO.id值填充ActivitiesProductsMO.activityId的每个数据库记录


如果我创建ID为555的活动记录
我将获得另一个activity_product记录,其activityId为555

我该如何工作?
谢谢!

最佳答案

与其手动尝试使用长值映射实体关系,不如使用从ActivityMO到ActivitiesProductsMO的双向OneToMany关系

将ActivitiesProductsMO更改为:

@Entity
@Table(name = "ACTIVITIES_PRODUCTS")
public class ActivitiesProductsMO {

    // cut unimportant code ...

    @ManyToOne
    @JoinColumn(name = "CAP_ACTIVITY_ID")
    private ActivityMO activityId;

    // cut unimportant code ...

}


如果随后要保留一个在其相关产品列表中已经具有ActivityProductsMO条目的ActivityMO,则级联类型实际上应该注意并创建那些产品,同时用正确的值填充CAP_ACTIVITY_ID数据库字段。

另一个可能的解决方案:

使用单向OneToMany:

@Entity
@Table(name = "ACTIVITIES")
public class ActivityMO extends ModelBase {

    @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
    @Fetch(FetchMode.JOIN)
    @JoinColumn(name = "CAP_ACTIVITY_ID")
    List<ActivitiesProductsMO> relatedProducts;


}


并删除

private Long activityId;


从您的ActivitiesProductsMO类中获得。

这都将导致相同的数据库结构。但是在第二种情况下,您将不再在Java中从ActivityProductsMO到ActivityMO的“反向链接”

关于java - Hibernate-在插入时填充子实体,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40893963/

10-08 22:36