我想知道如何通过 REST 调用删除多对多关联。我能够创建记录并关联它们,但不知道如何删除。
我有一个 Spring Boot 项目,我使用 REST 和 HATEOAS 绕过服务和 Controller 并直接公开我的存储库。
我有一个用户模型/域类
@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...
如您所见,我有一个 角色 成员,它与 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"
}
最佳答案
尽管使用剩余元素创建 PUT
请求可以解决问题,但 DELETE
是一个可以接受的删除关联资源的命令,并且在大多数情况下更易于使用。
至于你的例子,这应该有效:
DELETE localhost:8080/resttest/users/7/roles/4
另请注意,在创建关联时,预期负载中包含 URI。您不需要在正文中写入整个 URL,这应该足够了:
PUT localhost:8080/resttest/users/7/roles
Content-type: uri-list
Body: /roles/4
希望这可以帮助。
关于spring - 在 Spring Data REST+HATEOAS 中删除 REST 上的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28711439/