@JsonIgnoreProperties无法正常工作
我正在编写一对多关系,一个属性可以具有propertySale,我尝试使用@JsonIgnoreProperties来避免无限递归,但是由于某些原因,当我尝试保存propertySale时它不起作用。有人请告诉我我在哪里做错了吗?
在Property.java中
@Data
@Getter
@Entity
@Table(name = "Property")
public class Property {
@Id
@GeneratedValue
private Long id;
...
@OneToMany(mappedBy="property", cascade = CascadeType.ALL, targetEntity = PropertySale.class)
@JsonIgnoreProperties("property")
private Set<PropertySale> propertySales = new HashSet<>();
...
public void addPropertySale(PropertySale propertySale){
this.propertySales.add(propertySale);
}
}
在PropertySale.java
中@Data
@Getter
@Entity
@Table(name = "PropertySale")
public class PropertySale {
@Id
@GeneratedValue
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "property_id", referencedColumnName = "id")
@JsonIgnoreProperties("propertySales")
private Property property;
...
在PropertySaleServiceImp.java
中@Service
public class PropertySaleServiceImp implements PropertySaleService{
@Autowired
private PropertySaleRepository propertySaleRepository;
@Autowired
private PropertyRepository propertyRepository;
@Override
public ResponseEntity<PropertySale> savePropertySale(PropertySale propertySale) {
Optional<Property> existPropertyOpt = this.propertyRepository.findById(propertySale.getProperty().getId());
if(existPropertyOpt.isPresent()){
Example<PropertySale> propertySaleExample = Example.of(propertySale);
Optional<PropertySale> existPropSale = this.propertySaleRepository.findOne(propertySaleExample);
if(existPropSale.isPresent()){
throw new PropertySaleAlreadyExistException();
}else{
Property existProperty = existPropertyOpt.get();
propertySale.setProperty(existProperty);
existProperty.addPropertySale(propertySale);
this.propertyRepository.save(existProperty);
return new ResponseEntity<>(propertySale, HttpStatus.CREATED);
}
}else{
throw new PropertyNotFoundException(propertySale.getProperty().getId());
}
}
我明白了
org.springframework.web.util.NestedServletException:处理程序派发失败;嵌套的异常是java.lang.StackOverflowError
当行this.propertyRepository.save(existProperty);
被执行。