我想知道如何通过 REST 调用删除多对多关联。我能够创建记录并将它们关联起来,但不知道如何删除。
我有一个 Spring Boot 项目,其中使用 REST 和 HATEOAS 来绕过服务和控制器并直接公开我的存储库。
我有一个用户模型/域类
@Entity
@Table(name = "usr")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Version
private long version = 0;
@Id
@GeneratedValue(generator="optimized-sequence")
private Long id;
@Column(nullable = false, unique = true, length = 500)
@Size(max = 500)
private String userName;
@Column(nullable = false, length = 500)
@Size(max = 500)
private String firstName;
@Column(nullable = false, length = 500)
@Size(max = 500)
private String lastName;
@ManyToMany( fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable( name="user_role",
joinColumns={ @JoinColumn( name = "user_id",
nullable = false
)
},
inverseJoinColumns={ @JoinColumn( name="role_id",
nullable=false
)
}
)
private Set<Role> roles = new HashSet<Role>(0);
...Getters/Setters Below...
正如你所看到的,我有一个roles与Role类进行多对多关联的member,其代码如下:
@Entity
public class Role {
@Id
@GeneratedValue(generator="optimized-sequence")
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String description;
...Getters/Setters Below...
My 存储库看起来像这样:
用户存储库
public interface UserRepository extends
JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
List<User> findByUserName(String username);
}
角色库
public interface RoleRepository
extends JpaRepository<Role, Long> {
}
现在,一切都好。当我从浏览器访问项目根目录时,我得到 JSON+HAL 格式的存储库索引/目录。精彩的。
(请注意,我从下面的测试中删除了 http:// 部分,因为 StackOverflow 将其计入我的链接配额)
我使用 WizTools REST 客户端、HTTP.POST 到角色 ( localhost:8080/resttest/roles ) 存储库并创建一个新角色。成功,已创建角色 ID #4。
然后我 POST 到用户存储库以创建一个用户 ( localhost:8080/resttest/users )。成功,用户 ID #7 创建。
然后我将其放入用户存储库以创建与角色的关联:
PUT localhost:8080/resttest/users/7/roles
Content-type: uri-list
Body: localhost:8080/resttest/roles/4
伟大的!协会作出。用户 9 现在与角色 4 关联。
现在我无法弄清楚如何删除这个关联。
我使用与上面相同的命令发送 HTTP DELETE 而不是 PUT。
DELETE localhost:8080/resttest/users/7/roles
Content-type: uri-list
Body: localhost:8080/resttest/roles/4
我得到回复:HTTP/1.1 405 Method Not allowed
{
"timestamp":1424827169981,
"status":405,
"error":"Method Not Allowed",
"exception": "org.springframework.web.HttpRequestMethodNotSupportedException",
"message":"Request method 'POST' not supported"
}