1:n禁用n侧约束?



问题

我有一个1:n的关系,但是n边不应该依赖于约束。所以我实际上想通过它的未来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 "target"关系吗?它应该只将给定的ID插入到数据库中,而忽略EntityPojo是否真的存在。

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

要获得更简单的解决方案,请参阅下面的EDIT

如果目标是在不影响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,并且如果稍后插入该id的EntityPojo, Hibernate将知道如何正确地填充relationship。需要注意的是一个更复杂的域模型,并且您需要使用entityId属性而不是来控制RelationshipEntityPojoEntityPojo之间的关联。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<>();

唯一的警告是,当您尝试在插入缺失的EntityPojo之前加载RelationshipPojo.targets时,Hibernate会报错缺失的实体,因为显然@ManyToMany忽略了@NotFound

最新更新