这个java模型@oneToMany为什么返回的是递归结果?

最近刚学到Java的JPA
我现在有一个customer模型:

package com.example.demo.model.po;

import lombok.Data;

import org.hibernate.annotations.Fetch;

import org.hibernate.annotations.FetchMode;

import javax.persistence.*;

import java.util.HashSet;

import java.util.Set;

@Entity

@Table

@Data

public class Customer {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

@OneToMany(mappedBy = "customer")

@Fetch(value = FetchMode.SELECT)

private Set<Order> orders = new HashSet<>();

}

一个order

package com.example.demo.model.po;

import lombok.*;

import org.hibernate.Hibernate;

import javax.persistence.*;

import java.util.Objects;

@Entity

@Table(name = "orders")

@Getter

@Setter

@ToString

@RequiredArgsConstructor

public class Order {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String name;

@ManyToOne

@JoinColumn(name = "customer_id")

private Customer customer;

@Override

public boolean equals(Object o) {

if (this == o) return true;

if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;

Order order = (Order) o;

return id != null && Objects.equals(id, order.id);

}

@Override

public int hashCode() {

return getClass().hashCode();

}

}

控制器使用

package com.example.demo.controller;

import com.example.demo.model.po.Customer;

import com.example.demo.repository.CustomerRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;

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

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

import org.springframework.web.bind.annotation.RequestMapping;

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

@RestController

@RequestMapping("/api/customer")

public class CustomerController {

@Autowired

private CustomerRepository repo;

@GetMapping("/{id}")

public ResponseEntity<Customer> findById(@PathVariable Long id){

Customer customer = repo.findById(id).get();

return ResponseEntity.ok(customer);

}

}

返回的结果像这样:

{

"id": 1,

"orders": [

{

"id": 1,

"name": "ONE",

"customer": {

"id": 1,

"orders": [

{

"id": 1,

"name": "ONE",

"customer": {

"id": 1,

"orders": [

{

"id": 1,

"name": "ONE",

"customer": {

"id": 1,

"orders": [

{

"id": 1,

"name": "ONE",

"customer": {

"id": 1,

"orders": [

//...还有很多层

}

是哪里写的不对吗?请大佬指教,谢谢。


回答:

你用spring jpa就最好不要让@XxxToXxx这种注解参与序列化与反序列化

组好的办法是加上 transient 关键字,因为只要是正规的工具都会对transient关键字默认不处理, 你也以找一下其他注解,

  • 还有不要将这种懒加载的数据放到toString
  • 还有不要将这种懒加载的数据放到toString
  • 还有不要将这种懒加载的数据放到toString

以上是 这个java模型@oneToMany为什么返回的是递归结果? 的全部内容, 来源链接: utcz.com/p/944429.html

回到顶部