In the Category Entity below, a category can have parent category and also each category can have multiple children categories. Represented by the OneToOne and OneToMany relationships respectively. However, hibernate is enforcing unique constraints on the parent_id FK, which should not be the case, since this won’t allow children categories to have same parent. I’ve tried getting around this but am yet to find a solution to it, how do I resolve the issue?
package com.shopme.common.entity;
import jakarta.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "categories")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(length = 128, nullable = false, unique = true)
private String name;
@Column(length = 64, nullable = false, unique = true)
private String alias;
@Column(length = 128, nullable = false)
private String image;
private boolean enabled;
@OneToOne
@JoinColumn(name = "parent_id", unique = false)
private Category parent;
@OneToMany(mappedBy = "parent")
private Set<Category> children = new HashSet<>();
public Category(Integer id) {
this.id = id;
}
public Category(String name ){
this.name = name;
this.alias = name;
this.image = "default.png";
}
public Category(String name, Category parent ){
this(name);
this.parent = parent;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Category getParent() {
return parent;
}
public void setParent(Category parent) {
this.parent = parent;
}
public Set<Category> getChildren() {
return children;
}
public void setChildren(Set<Category> children) {
this.children = children;
}
}
SQL LOG
Hibernate:
create table categories (
id integer not null auto_increment,
alias varchar(64) not null,
enabled bit not null,
image varchar(128) not null,
name varchar(128) not null,
parent_id integer,
primary key (id)
) engine=InnoDB
Hibernate:
alter table categories
drop index UK_jx1ptm0r46dop8v0o7nmgfbeq
Hibernate:
alter table categories
add constraint UK_jx1ptm0r46dop8v0o7nmgfbeq unique (alias)
Hibernate:
alter table categories
drop index UK_t8o6pivur7nn124jehx7cygw5
Hibernate:
alter table categories
add constraint UK_t8o6pivur7nn124jehx7cygw5 unique (name)
Hibernate:
alter table categories
drop index UK_2n3awjv8ah4gl5ca1bq26sori
Hibernate:
alter table categories
add constraint UK_2n3awjv8ah4gl5ca1bq26sori unique (parent_id)
Hibernate:
alter table categories
add constraint FKsaok720gsu4u2wrgbk10b5n8d
foreign key (parent_id)
references categories (id)