我有一个名为data.sql的文件,其中包含SQL查询“ INSERT INTO”。 我有表User,哪个模型是:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
// other fields
@OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "user")
@Column(name = "vacations")
private Set<Vacation> vacations = new HashSet<>();
我的度假模型在哪里:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column(name = "begin_date")
private LocalDateTime beginDateOfVacation;
@NotNull
@Column(name = "end_date")
private LocalDateTime endDateOfVacation;
@NotEmpty
@Column(name = "type")
private String typeOfVacation;
@NotEmpty
@Column(name = "reason")
private String reasonOfVacation;
@ManyToOne(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
然后在我的data.sql中,我尝试将具有现有ID的Vacation User插入。 它“传递”了编译器,但是在localhost上我只能看到以下内容:
无法编写JSON:无限递归(StackOverflowError);嵌套的异常是com.fasterxml.jackson.databind.JsonMappingException:无限递归(StackOverflowError)(通过参考链:com.springproject27.springproject.user.User [“ vacations”])
这是H2数据库引擎,我尝试传递的查询是:
插入假期(ID,BEGIN_DATE,END_DATE,TYPE,REASON,USER_ID)VALUES (22,'2012-09-17 18:47:52.69','2012-09-20 18:47:52.69','无薪假期','病假',10);
答案 0 :(得分:0)
由于User
实体与Vacation
实体之间的双向关系,当您尝试序列化数据时,由于JSON递归您会看到它的发生。使用@JsonIgnoreProperties
(如果您使用的是Jackson 2.0+版本)在序列化过程中中断递归的首选方法。
注意:破坏JSON递归的另一种方法是结合使用JsonBackReference和JsonManagedReference。但是我更喜欢@JsonIgnoreProperties
,因为在序列化过程中不会丢失数据。
如果您使用的是
Lombok
,请仅使用@Getter和@Setter批注而不使用@ToString(或包含@ToString的@Data),因为这会导致相同的递归问题。
class User{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
// other fields
@OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "user")
@Column(name = "vacations")
@JsonIgnoreProperties("user")
private Set<Vacation> vacations = new HashSet<>();
}
class Vacation{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column(name = "begin_date")
private LocalDateTime beginDateOfVacation;
@NotNull
@Column(name = "end_date")
private LocalDateTime endDateOfVacation;
@NotEmpty
@Column(name = "type")
private String typeOfVacation;
@NotEmpty
@Column(name = "reason")
private String reasonOfVacation;
@ManyToOne(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
@JsonIgnoreProperties("vacations")
private User user;
}