需要一些REST api的帮助,以便使用spring数据休息来实现Employee和Role之间的多对多关系
@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 Data Repository:
import org.springframework.data.repository.CrudRepository;
public interface EmployeeRepository extends CrudRepository<Employee, Long>{}
从其余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的顺序。
感谢任何帮助或建议。
答案 0 :(得分:0)
改变SDR中角色集合的正确机制是发送PATCH请求,如下所示:
{
"roles": [
"http://localhost:8091/roles/adm",
"http://localhost:8091/roles/usr"
]
}
然而,请参阅Hopper SR5中的以下回归,并在Hooper SR9中修复。