我正在使用 Jersey 实现一个 RESTful Web 服务。我使用休眠与数据库(mySQL)进行通信。我的休眠资源类包括:
@Entity
public class Activity {
@Id
@GeneratedValue
private long id;
@ManyToOne
@JoinTable(name="category_activity",
joinColumns={@JoinColumn(name="activities_id")},
inverseJoinColumns={@JoinColumn(name="Category_id")})
private Category category;
}
和类别类:
@Entity
public class Category {
@Id
@GeneratedValue
private long id;
@OneToMany
@Fetch(FetchMode.JOIN)
@JoinTable(name = "category_activity",
joinColumns = { @JoinColumn(name = "Category_id") },
inverseJoinColumns = { @JoinColumn(name = "activities_id") })
@JsonIgnore
private Collection<Activity> activities;
}
我使用此查询来获取活动:
session.createQuery("from Activity a join a.category cs where cs.id= :categoryId order by a.key").setLong("categoryId", categoryId).list();
JSON 格式的结果不正确,例如:
[[{"id":26,"key":"other","name":"Other","cost":100.0,"category":{"id":10,"name":"General","description":""}},{"id":10,"name":"General","description":""}]]
如您所见,类别被打印了 2 次,并且我们在它周围有一个额外的 []。当我在 Category 类中使用另一种一对多关系机制时,例如:
@OneToMany(targetEntity = Activity.class, mappedBy = "category", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonIgnore
private Collection<Project> activities;
在 Activity 类中:
@ManyToOne(optional = false)
private Category category;
这个查询:
session.createQuery("from Activity as a where a.category.id= :categoryId order by a.key").setLong("categoryId", categoryId).list();
一切正常。但我必须使用连接表,因为我不打算更改数据库。
正确的结果应该如下所示:
[{"id":26,"key":"other","name":"Other","cost":100.0,"category":{"id":10,"name":"General","description":""}}]
我很感激任何帮助。