Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc控制器和复合主键_Spring_Spring Mvc_Jpa_Spring Data Jpa - Fatal编程技术网

Spring mvc控制器和复合主键

Spring mvc控制器和复合主键,spring,spring-mvc,jpa,spring-data-jpa,Spring,Spring Mvc,Jpa,Spring Data Jpa,我有一个带有复合主键的实体,用@IdClass注释。表示PK的类是可序列化的,因此我能够为实体创建JPA存储库 现在,我想创建一个控制器,其中一个操作是通过其ID获取一个实体。对于具有简单PKs(即整数)的其他实体,这很简单: 使用路径变量调用控制器/操作:myurl/controlles/action/1 我得到id(本例中为1)变量,在存储库中,我可以调用findOne(id) 但是对于复合PK,我想我应该在某个地方指定如何序列化/反序列化它。例如,我会调用myurl/controllers

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

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

使用路径变量调用控制器/操作:
myurl/controlles/action/1

我得到
id
(本例中为1)变量,在存储库中,我可以调用
findOne(id)

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


我的方向正确吗?

只需将路径值与角色中的任何内容放在一起,即可分离组合键

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);
    }

}
输入

输出

firstKey = ABCDEF
secondKey = 123456

为什么不创建一个包含所有主键的类,并将其作为控制器中的参数接受呢?但我如何将其作为路径变量接收?(或GET参数)您应该将其作为RequestBody而不是Path变量接受。当您有更多变量时,接受为pathvariable不是一个好主意。在这种情况下,您的url将太长
firstKey = ABCDEF
secondKey = 123456