代码之家  ›  专栏  ›  技术社区  ›  genaray

1:n是否禁用n侧的约束?

  •  0
  • genaray  · 技术社区  · 4 年前

    问题所在

    我有一个1:n的关系,但n侧不应该依赖于约束。所以我实际上想在EntityPojo尚未保存时,通过其未来的id插入一个EntityPojo(让我们忽略这是一种糟糕的做法)。这看起来有点像这样。

    
    var relation = new RelationshipPojo();
    .
    .
    .
    relation.targets.add(session.getReference(futureID, EntityPojo.class));
    session.save(relation);
    
    // A few frames later
    session.save(theEntityPojoWithTheSpecificId);
    

    级联在这里是不可能的,我只有它的未来ID,没有对我想保存的对象的引用。只有它的id在未来会有的。

    @Entity
    @Table(name = "relationship")
    @Access(AccessType.FIELD)
    public class RelationshipPojo {
    
        .
        .
        .
    
        @ManyToMany(cascade = {}, fetch = FetchType.EAGER)
        public Set<EntityPojo> targets = new LinkedHashSet<>();
    }
    

    提问

    我们如何告诉hibernate它应该忽略这个1:n“目标”关系的约束?它应该只将给定的ID插入数据库,忽略EntityPojo是否真的存在。

    很高兴在这个话题上得到任何帮助,谢谢!

    0 回复  |  直到 4 年前
        1
  •  2
  •   crizzis    4 年前

    有关更简单的解决方案,请参阅下面的编辑

    如果目标是在连接表中插入行,而不影响 ENTITY_POJO 在表中,您可以将多对多关联建模为实体本身:

    @Entity
    @Table(name = "relationship")
    @Access(AccessType.FIELD)
    public class RelationshipPojo {
    
        @OneToMany(cascade = PERSIST, fetch = EAGER, mappedBy = "relationship")
        public Set<RelationShipEntityPojo> targets = new LinkedHashSet<>();
    }
    
    @Entity
    public class RelationShipEntityPojo {
    
        @Column(name = "entity_id")
        private Long entityId;
    
        @ManyToOne
        private RelationshipPojo relationship;
    
        @ManyToOne
        @NotFound(action = IGNORE)
        @JoinColumn(insertable = false, updatable = false)
        private EntityPojo entity;
    }
    

    这样,您就可以为 entityId 属性转换为不存在的id,如果 EntityPojo 通过稍后插入id,Hibernate将知道如何填充 relationship 正确。需要注意的是,这是一个更复杂的领域模型,而且你需要控制它们之间的关联 RelationshipEntityPojo 实体Pojo 使用 实体Id 财产, entity .

    编辑实际上,忽略上述答案,它过于复杂。Turing85是正确的,因为你应该简单地删除约束。您可以使用以下命令阻止Hibernate首先生成它:

        @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
        @JoinTable(inverseJoinColumns = @JoinColumn(name = "target_id", foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT)))
        public Set<EntityPojo> targets = new LinkedHashSet<>();
    

    唯一需要注意的是,当您尝试加载时 RelationshipPojo.targets 在插入缺失之前 实体Pojo ,Hibernate会抱怨缺少实体,很明显 @NotFound 被忽略 @ManyToMany .