【发布时间】:2017-09-09 18:48:21
【问题描述】:
需要一些关于 REST api 的帮助,以使用 spring 数据休息来处理员工和角色之间的多对多关系
@Entity
@Table(name="employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="employees_id_seq")
@SequenceGenerator(name="employees_id_seq", sequenceName="employees_id_seq", allocationSize=1)
@Column(name="EMPLOYEE_ID")
private Long id;
@NotNull
private String email;
@ManyToMany(cascade={}, fetch=FetchType.EAGER, targetEntity=Role.class)
@JoinTable(
name="employee_roles",
joinColumns=@JoinColumn(name="EMPLOYEE_ID", referencedColumnName="EMPLOYEE_ID"),
inverseJoinColumns = @JoinColumn(name="ROLE_ID", referencedColumnName="ROLE_ID")
)
private List<Role> roles;
public Employee() {
System.out.println("Employee created");
}
public Employee(long id, String firstName, String lastName, String email) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
// Getters , Setter, etc.
}
@Entity
@Table(name="roles")
public class Role {
@Id
@Column(name="ROLE_ID")
private String roleId;
private String roleName;
public Role() {
}
// Getters, Setters, etc
}
Spring 数据存储库:
import org.springframework.data.repository.CrudRepository;
public interface EmployeeRepository extends CrudRepository<Employee, Long>{}
从rest api收到的以json表示的当前数据库状态:
{
"firstName": "First1",
"lastName": "Last1",
"email": "first_last@acme.com",
"roles": [ {"roleName": "User"}, {"roleName": "Admin"}],
"locationId": 43,
"_links": {
"self": {
"href": "http://localhost:8091/employees/1"
},
"employee": {
"href": "http://localhost:8091/employees/1"
}
}
}
我在数据库中有以下角色数据:
从角色中选择role_id、role_name
role_id role_name
------- -------
adm Admin
usr User
我想删除用户角色并保留用户的管理员角色。我正在尝试将 PATCH 请求与以下有效负载一起使用
{
"roles": [ {"roleId": "adm"}]
}
不幸的是它导致了错误:
org.hibernate.HibernateException: Role 实例的标识符已从 usr 更改为 adm
如果我尝试使用有效负载删除角色 Admin
{
"roles": [ {"roleId": "usr"}]
}
效果很好。
似乎行为取决于角色 ID 的顺序。
感谢任何帮助或建议。
【问题讨论】:
标签: spring hibernate rest spring-data-jpa spring-data-rest