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?
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
.