我正在使用Hibernate将我的实体保存到数据库。举个简单的例子,我有两个实体:
汽车:
@Entity
@Table(name = "car")
public class Car implements Serializable {
@Id
@GeneratedValue
private long id;
private String name;
@OneToMany(cascade = CascadeType.PERSIST)
private List<Wheel> wheelList;
public Car() {
}
public Car(String name, List<Wheel> wheelList) {
this.name = name;
this.wheelList = wheelList;
}
和Wheel:
@Entity
@Table(name = "wheel")
public class Wheel implements Serializable {
@Id
@GeneratedValue
private long id;
private int size;
@ManyToOne(cascade = CascadeType.PERSIST)
private Car car;
public Wheel() {
}
public Wheel(int size, Car car) {
this.size = size;
this.car = car;
}
我正在使用Spring Framework(MVC)创建REST客户端,我从中返回JSON。 现在:我创建了简单的@Repository和@Service。
我想尝试保存工作,所以我用轮子列表等创建了简单的Car对象然后,在@Service层我保留了它并将car对象返回到控制器。
最后,当我从控制器运行url时,我收到了巨大的json,因为每个Car对象都有轮子列表,然后,每个轮子都有它的车,它还有列表,列表中有车轮和车轮所以..这就是为什么我的JSON如此之大。
{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":{"id":1,"name":"SomeName","wheelList":[{"id":1,"size":1,"car":...........
我做错了什么?我该如何解决这个问题?
如果你需要它的其余代码:(仅用于测试,我知道这里没有很好的编码风格) 存储库:
@Repository
public class TestImpl {
@PersistenceContext
private EntityManager entityManager;
public Car saveCar(Car car){
entityManager.persist(car);
return car;
}
}
服务
@Service
@Transactional
public class TestService {
@Autowired
private TestImpl test;
public Car save(){
Car car = new Car();
car.setName("SomeName");
List<Wheel> list = new ArrayList<Wheel>();
list.add(new Wheel(1, car));
car.setWheelList(list);
test.saveCar(car);
return car;
}
}
控制器:
@Controller
public class TestController {
@Autowired
private TestService testService;
@RequestMapping(value = "/los")
@ResponseBody
public Car los(){
return testService.save();
}
}
答案 0 :(得分:1)
您可以将@JsonIgnore
注释添加到wheelList
对象中的Car
字段或car
对象中的Wheel
字段。这将阻止JSON序列化程序在结果文档中显示这些字段,并以递归方式包含字段。