【发布时间】:2022-01-24 07:21:38
【问题描述】:
当我尝试保存多对多关系的实体(角色)时,子实体的 id 生成不正确,并且我收到 DataIntegrityViolationException。
用子实体保存父实体的一部分:
public Organization create(Organization organization) {
Organization created = save(organization);
Role role = new Role();
role.setCode("test");
created.getRoles().add(role);
return save(created);
}
休眠调试和异常:
Hibernate: insert into organization (company_code, full_legal_name, id) values (?, ?, ?)
Hibernate: insert into role (code, description, read_only, reserved) values (?, ?, ?, ?)
2021-12-23 10:34:50.459 WARN 13464 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23505
2021-12-23 10:34:50.459 ERROR 13464 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: duplicate key value violates unique constraint "role_pkey"
Detail: Key (id)=(15) already exists.
父实体:
@Entity
public class Organization {
@Id
Long id;
@ManyToMany(cascade = {CascadeType.ALL}, fetch= FetchType.EAGER)
@JoinTable(name = "organization_role",
joinColumns = @JoinColumn(name = "organization_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
Set<Role> roles = new HashSet<>();
}
角色实体:
@Entity
public class Role implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
}
Liquibase 表: 角色:
CREATE TABLE role
(
id SERIAL NOT NULL,
code VARCHAR(32) NOT NULL,
CONSTRAINT role_pkey PRIMARY KEY (id)
);
组织:
CREATE TABLE organization (
id bigint NOT NULL,
CONSTRAINT organization_pkey PRIMARY KEY (id)
);
组织-角色:
CREATE TABLE organization_role (
role_id INTEGER NOT NULL,
organization_id BIGINT NOT NULL,
CONSTRAINT fk_organization_role_role FOREIGN KEY (role_id) REFERENCES role(id),
CONSTRAINT fk_organization_role_organization FOREIGN KEY (organization_id) REFERENCES organization(id),
CONSTRAINT user_organization_pkey PRIMARY KEY (role_id, organization_id)
);
【问题讨论】:
标签: java spring-boot spring-data-jpa spring-data liquibase