我使用的泽西实现RESTful Web服务。 我使用Hibernate与数据库(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;
}
和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;
}
我用这个语句来抓取ativities:
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次,我们有一个额外的[]周围。 当我使用的一个一对多的关系,另一种机制范畴类,如:
@OneToMany(targetEntity = Activity.class, mappedBy = "category", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonIgnore
private Collection<Project> activities;
而在活动类:
@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":""}}]
我很欣赏的任何帮助。