如何在REST中处理@OneToMany关系

时间:2017-09-03 09:32:44

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

我正在设计一个允许执行一些基本操作的小型REST应用程序。到目前为止一切顺利,我跟随@Entity名为Client的{​​{1}}需要与名为@Entity的{​​{1}}保持一致:

客户端:

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 } 拒绝注册新贷款,并显示以下消息:

  

{       “timestamp”:1504429329213,       “身份”:400,       “错误”:“错误请求”,       “exception”:“org.springframework.http.converter.HttpMessageNotReadableException”,       “message”:“JSON解析错误:无法构造com.reborn.xxx.backend.models.Client的实例:没有int / Int-argument构造函数/工厂方法从Number值(1)反序列化;嵌套异常是com。 fasterxml.jackson.databind.JsonMappingException:无法构造com.reborn.xxx.backend.models.Client的实例:no int / int-argument构造函数/工厂方法从Number值(1)\ n反序列化[来源:java .io.PushbackInputStream @ 121b34b; line:3,column:12](通过引用链:com.reborn.xxx.backend.models.Loan [\“client \”])“,       “路径”:“/ api / loans / add”   }

LoanController:

PostMan

如何实现这一目标?

UPDATE1:

ClientRepository:

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

LoanRepository:

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

添加客户端(工作)的JSON:

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

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

{
"id": 1,
"name": "Arthur",
"surname": "Doyle",
"phone": 777458642,
"email": "adoyle@imperial.com"
}

1 个答案:

答案 0 :(得分:2)

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

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

不需要自定义控制器。

P.S。将@JsonIgnoreProperties("loans")添加到Loan.client以避免堆栈溢出异常...

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