spring-boot - 如何在运行时启用/禁用实体关系?

标签 spring-boot spring-data-jpa spring-data spring-data-rest

我有一个具有基本 CRUD 服务的 Spring Boot 应用程序。对于读取服务,我也想查看它们之间的关系。通过@ManyToOne、@OneToOne 等注释实现关系没有问题,如this。示例。

我的问题是我想根据列表服务中的参数启用此关系,或者我也可以使用另一个端点。我怎样才能做到这一点?欢迎提出任何建议。

  • 参数版本可以是 -> /employe/list?includeRelations=true
  • 端点版本可能是 -> /员工/列表/byRelations

我的实体是这样的;

    @Entity
    @Table(name = "employee")
    public class Employee{
        private long id;
        private String name;
        private Address address;
        
        // getter setters
    }
    
    @Entity
    @Table(name = "address")
    public class Address {
        private long id;
        private String name;
        private String postalCode;
    
        // getter setters
    }

编辑 例如

  • 没有 includeRelations=true '/employee/list' 服务应该返回这个;
{
    "id": 1,
    "name": "Jane"
}
  • includeRelations=true '/employee/list' 服务应该返回这个;
{
    "id": 1,
    "name": "Jane"
    "address": { 
                 "id":1,
                 "name": "HOME",
                 "postalCode": "11111"
                }
}

最佳答案

它的一些 sudo 代码供您理解。您可以使用 Query Parameter 并且在条件下您可以根据需要调用 repo : 对于我的场景,我想要不同的响应 shortmediumlong

@RequestMapping(value = "/getContacts", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, headers = "Accept=application/json") public String getContact(@RequestBody ContactItemRequestInfo contactItemRequestInfo, @RequestParam(required = false) 字符串键, 字符串联系) {

    if(key.equals("medium"))
    {
         return Contact="{\"responseCode\":\"02\",\"responseDescription\":\"Success\",\"totalCount\":2,\"contacts\":[{\"id\":114,\"firstName\":\"ali\",\"lastName\":\"kamran\"},{\"id\":115,\"firstName\":\"usman\",\"lastName\":\"khan\",\"middleName\":\"saad\"}]}";
         
    }
    else if(key.equals("long"))
    {
        return Contact="{\"responseCode\":\"03\",\"responseDescription\":\"Success\",\"totalCount\":2,\"contacts\":[{\"id\":114,\"firstName\":\"ali\",\"lastName\":\"kamran\"},{\"id\":115,\"firstName\":\"usman\",\"lastName\":\"khan\",\"middleName\":\"saad\"}]}";
        
    }
    else
    {
        return Contact="{\"responseCode\":\"00\",\"responseDescription\":\"Success\",\"totalCount\":2,\"contacts\":[{\"id\":114,\"firstName\":\"ali\",\"lastName\":\"kamran\"},{\"id\":115,\"firstName\":\"usman\",\"lastName\":\"khan\",\"middleName\":\"saad\"}]}";
        
    }

} 对你有帮助!!

关于spring-boot - 如何在运行时启用/禁用实体关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66915464/

相关文章:

java - 由于 kafka 流存储正在等待运行,应用程序无法启动

elasticsearch - Elasticsearch:请求[/some index/_refresh]包含无法识别的参数:[refresh]

java - native 查询 spring data JPA 的问题返回带有空对象的空 JSON 数组

java - 直接向 DTO 查询结果

java - 无法使用路径映射 Controller

spring-boot - spring boot RedisTemplate配置集群写对象很慢,如果单机很快,为什么?

java - Spring Data jpa 如何知道属性发生了变化?

java - Spring聚合框架: How to create nested $divide, $subtract,$mod查询?

java - 使用 Spring 数据调用自定义 mongoDB 查询失败

java - java中的时间戳 validator