所以我做了两个有一对多关系的实体, 我有一个类别有很多访客, 这是我的代码:
这是类别实体:
@Entity
public class Category implements Serializable {
private Integer id;
private String name;
private List<Visitor> visitors = new ArrayList<Visitor>();
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(cascade=CascadeType.REMOVE, fetch = FetchType.LAZY, mappedBy = "category", orphanRemoval = true)
public List<Visitor> getVisitors() {
return visitors;
}
public void setVisitors(List<Visitor> visitors) {
this.visitors = visitors;
}
}
这里是访客实体:
@Entity
public class Visitor extends User {
private String passport;
private String citizenship;
private String gender;
private Company company;
private Category category;
public String getPassport() {
return passport;
}
public void setPassport(String passport) {
this.passport = passport;
}
public String getCitizenship() {
return citizenship;
}
public void setCitizenship(String citizenship) {
this.citizenship = citizenship;
}
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
以下是列出所有访问者并且工作正常的服务方法:
public List<Visitor> findAllVisitors() {
return em.createQuery(
"SELECT v from Visitor v left join fetch v.category",
Visitor.class).getResultList();
}
通过这种方法,我可以列出每个与其类别对象相关联的访问者,
现在问题出在关系的另一边, 以下是列出每个类别及其访问者列表的方法:
public List<Category> findAllCategories() {
return em.createQuery("select c from Category c",
Category.class).getResultList();
}
我想获取所有类别的列表但是当我在REST调用中调用此方法时,我得到了这个结果:
我想要一个简单的类别列表(id和name)。 我的代码有什么问题请帮助我,我很困惑。
更新:
这是我如何使用RESTful方法从持久化上下文中获取JSON:
@Inject
private CategoryServiceLocal categoryServiceLocal;
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Category> dofindAllCategories() {
return categoryServiceLocal.findAllCategories();
}
答案 0 :(得分:0)
您有Category
到visitors
之间的懒惰关联。要加载所有访问者,您也需要使用left join fetch
。
select c from Category c left join fetch c.visitors
请使用其他注释来控制JSON
生成的方式
Infinite Recursion with Jackson JSON and Hibernate JPA issue