【问题标题】:Spring mvc controller and composite primary keysSpring mvc 控制器和复合主键
【发布时间】:2018-06-01 20:00:22
【问题描述】:

我有一个带有复合主键的实体,用@IdClass 注释。代表 PK 的类是可序列化的,因此我能够为实体创建 JPA 存储库。

现在,我想创建一个控制器,其中一个操作是通过 ID 获取一个实体。对于其他具有简单 PK 的实体(即整数),这很简单:

使用 Path 变量调用控制器/动作:myurl/controlles/action/1

我得到了id(在这种情况下为1)变量,在存储库中,我可以调用findOne(id)

但是对于复合 PK,我想我应该在某处指定如何序列化/反序列化它。例如,我会调用myurl/controllers/action/firstPKfield-secondPKfield,然后在某处告诉控制器它应该从两个字段由- 分隔的字符串创建一个PK 复合键。

我的方向是否正确?

【问题讨论】:

  • 为什么不创建一个包含所有主键的类并在控制器中接受它作为参数
  • 但是我怎样才能将它作为路径变量接收呢? (或 GET 参数)
  • 您应该接受它作为 RequestBody 而不是 Path 变量。当您有更多变量时,接受作为路径变量并不是一个好主意。在这种情况下,您的网址将太长

标签: spring spring-mvc jpa spring-data-jpa


【解决方案1】:

只需将您的路径值与您的角色放在一起,以分隔您的复合键。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE;

@RestController
public class Controller {

    @GetMapping(value = "/poc/{firstKey}_{secondKey}", produces = TEXT_PLAIN_VALUE)
    public String getResponse(@PathVariable String firstKey, @PathVariable String secondKey) {

        return String.format("firstKey = %s\nsecondKey = %s", firstKey, secondKey);
    }

}

输入

$ curl http://localhost:8080/controller/poc/ABCDEF_123456

输出

firstKey = ABCDEF
secondKey = 123456

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多