我对 @JsonIdentityInfo
有疑问。我在 json 文件中得到两个 id。
{
"name" : "Tim",
"@id" : 1, // fasterxml garbage
"id" : 3,
"company" : {
"name" : "Microsoft",
"employees" : [1], // garbage too
"@id" : 2, // fasterxml garbage
"id" : 3
}
}
这是我的实体:
@Entity
@Table(name = "company")
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "id")
public class Company implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column
private String name;
@OneToMany(mappedBy = "company")
@Cascade(value = CascadeType.ALL)
private Collection<Employee> employees;
如何删除不需要的Id?
更新:
我正在使用com.fasterxml.jackson
最佳答案
这是一个老问题,你现在可能已经得到答案了,但是从阅读它来看,你的额外 id 问题似乎来自于你使用的生成器。
IntSequenceGenerator
将使 Jackson 生成自动递增的 id,并且您指定希望它们作为 id
属性(并且您已经有一个 id
属性,我想这就是 Jackson 生成 @id
的原因)。您希望 Jackson 使用现有的 id
属性,为此您只需使用 PropertyGenerator
即可。
您还需要在注释上使用 scope
属性,并在 Employee
类上使用它,因为您有两个独立的 id 序列。
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope=Company.class)
public class Company {}
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope=Employee.class)
public class Employee {}
这应该为您的示例生成
{
"name" : "Tim",
"id" : 3,
"company" : {
"name" : "Microsoft",
"employees" : [3],
"id" : 3
}
}
关于java - 如何删除@JsonIdentityInfo不必要的Id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23071662/