json - 如何在 REST 中处理 @OneToMany 关系

标签 json spring hibernate spring-data-jpa spring-rest

我正在设计一个小REST允许执行一些基本操作的应用程序。到目前为止一切顺利,我有以下@EntityClient需要与 @Entity 一起坚持下去叫Loan :

客户:

@Entity
@Table(name = "clients")
public class Client{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "CLIENT_ID")
    private Long id;

    private String name;
    private String surname;
    private String email;
    private String phone;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "client")
    private Set<Loan> loans;

    public Client() {}

    public Client(Long id, String name, String surname, String email, String phone) {
        this.id = id;
        this.name = name;
        this.surname = surname;
        this.email = email;
        this.phone = phone;
    }

   // getters/setters

}

贷款:

@Entity
@Table(name = "loans")
public class Loan{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "CLIENT_ID")
    private Client client;

    @Temporal(TemporalType.DATE)
    private Date startDate = new Date();

    @Temporal(TemporalType.DATE)
    private Date originTerm;

    private Float maxPossibleAmount;

    private String notes;

    public Loan() {}

    public Loan(Long id, Client client, Date startDate, Date originTerm, Float maxPossibleAmount, String notes) {
        this.id = id;
        this.client = client;
        this.startDate = startDate;
        this.originTerm = originTerm;
        this.maxPossibleAmount = maxPossibleAmount;
        this.notes = notes;
    }

 // getters/setters
}

通过 postman 注册客户工作完美,但是我无法理解如何为特定客户注册贷款。尝试这样做时,PostMan拒绝注册新贷款并显示以下消息:

{ "timestamp": 1504429329213, "status": 400, "error": "Bad Request", "exception": "org.springframework.http.converter.HttpMessageNotReadableException", "message": "JSON parse error: Can not construct instance of com.reborn.xxx.backend.models.Client: no int/Int-argument constructor/factory method to deserialize from Number value (1); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.reborn.xxx.backend.models.Client: no int/Int-argument constructor/factory method to deserialize from Number value (1)\n at [Source: java.io.PushbackInputStream@121b34b; line: 3, column: 12] (through reference chain: com.reborn.xxx.backend.models.Loan[\"client\"])", "path": "/api/loans/add" }

贷款 Controller :

@RestController
@RequestMapping(value = "/api/loans")
public class LoanController extends BaseController {

    @Autowired
    private LoanService loanService;

    @RequestMapping(value = "/add", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity registerLoan(@RequestBody Loan loan) {
        Loan regLoan = loanService.registerLoan(loan);
        if(regLoan == null) {
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(HttpStatus.CREATED);
    }
}

有什么想法可以实现这个目标吗?

更新1:

客户端存储库:

@Repository
public interface ClientRepository extends JpaRepository<Client, Long>{
}

贷款存储库:

@Repository
public interface LoanRepository extends JpaRepository<Loan, Long> {
}

用于添加客户端的 JSON(有效):

{
"id": 1,
"name": "Arthur",
"surname": "Doyle",
"phone": 777458642,
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="28494c4751444d684145584d5a414944064b4745" rel="noreferrer noopener nofollow">[email protected]</a>"
}

向特定客户提供贷款的 JSON(失败):

{
    "id": 1,
    "client": "http://loacalhost:8080/api/clients/find/1",
    "startDate": 20170902,
    "originTerm": 20170902,
    "maxPossibleAmount": 5555.0000,
    "notes": null
}

最佳答案

您的贷款客户相关联。因此,如果您想为客户创建贷款,请使用以下有效负载:

POST http://loacalhost:8080/api/loans 
{
    "originTerm": ...
    "maxPossibleAmount": ...
    "notes": ...
    "client": "http://loacalhost:8080/api/clients/1"
}

不需要自定义 Controller 。

附注将 @JsonIgnoreProperties("loans") 添加到 Loan.client 以避免 stackoverflow 异常...

P.P.S。在 @OneToMany 中,fetch 参数默认为 FetchType.LAZY,因此您可以避免使用它。

关于json - 如何在 REST 中处理 @OneToMany 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46022047/

相关文章:

java - Spring Boot 增删改查存储库

java - Hibernate - 保留可嵌入资源

sql - 使用 Snowflake SQL 解析 JSON

javascript - 在 React.js 中过滤 JSON 数据

javascript - 在javascript中循环遍历json多维数组

java - 如何在Android中显示统计数据等数据?

Spring MVC 应用程序不接受 JSON

java - Spring MVC - 表单映射

java - 是否可以在带有 Hibernate 和 AspectJ 的 Java 项目中使用 SBT?

java - findAll() 在 SpringBoot Rest MySql CRUD 操作应用程序中不起作用