【发布时间】:2015-04-26 23:59:07
【问题描述】:
我想知道如何通过 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 类是多对多关联,其代码如下:
@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...
我的存储库如下所示:
用户存储库
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 到用户存储库以创建与角色的关联:
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"
}
【问题讨论】:
-
请问有什么解决办法!?
标签: spring rest spring-data-rest spring-hateoas