英文:
Hibernate Onetomany self join adds unique constraint
问题
@Entity
public class Layer {
@Id
private Long id;
@Column(name = "PARENT_ID")
private String parentId;
@OneToMany
@JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", updatable = false, insertable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private Set
}
This means that I want to get all the other entities sharing the same 'parentId'. The reason I want it is because it would be easier to write queries for this entity.
The problem is that on database generation ('spring.jpa.properties.hibernate.hbm2ddl.auto=create'), it also adds a unique constraint on the 'PARENT_ID' column, and I do not want that.
How do I keep Hibernate from adding the unique constraint?
英文:
I would like to add a one to many relationship of an entity with itself:
@Entity
public class Layer {
@Id
private Long id;
@Column(name = "PARENT_ID")
private String parentId;
@OneToMany
@JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", updatable = false, insertable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private Set<Layer> siblings;
}
This means that I want to get all the other entities sharing the same parentId
. The reason I want it is because it would be easier to write queries for this entity.
The problem is that on database generation(spring.jpa.properties.hibernate.hbm2ddl.auto=create
) it also adds a unique constraint on the PARENT_ID
column and I do not want that.
How do I keep hibernate from adding the unique constraint?
答案1
得分: 0
你的映射目前使得 children
通过列 PARENT_ID
引用它们的父级。为了将某个内容用作引用,它必须是唯一的。
你可能希望将子级通过其 id
引用其父级。
以下代码可以实现这个目标:
@OneToMany
@JoinColumn(name = "PARENT_ID", referencedColumnName = "ID", updatable = false, insertable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private Set<Layer> children;
我不确定你是否还可以有一个 String parentId
。首先,它映射到与 children
属性相同的列,但类型不同:id
的类型是 Long
,而应引用它的 parentId
的类型是 String
。
正常的做法是创建一个属性 Layer parent
,并使用 @ManyToOne
和 mappedBy
与 children
关联。
英文:
Your mapping currently makes children
reference their parent by the column PARENT_ID
. In order to use something as a reference it has to be unique.
What you probably want to have is the children to reference their parent by its id
.
This should do the trick:
@OneToMany
@JoinColumn(name = "PARENT_ID", referencedColumnName = "ID", updatable = false, insertable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private Set<Layer> children;
I'm not sure that you can have a String parentId
as well.
First it maps to the same column as the children
property, but with a different type: id
is of type Long
, while parentId
which should reference it is of type String
.
The normal way to do this would be to make a property Layer parent
which @ManyToOne
and mappedBy
children
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论