9

我正在使用 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":""}}]

我很感激任何帮助。

4

1 回答 1

19

在多方面定义连接表,但不要在一侧再次定义它。这会创建两个映射到同一个表的单向关联,而不是一个双向关联。

双向关联总是有一个所有者端(您可以在其中指定要使用的连接列或连接表,以及一个反向端,它使用 mappedBy 属性表示它是另一端的反向:

public class Activity {

    @ManyToOne // owner side: it doesn't have mappedBy, and can decide how the association is mapped: with a join table
    @JoinTable(name="category_activity",
               joinColumns={@JoinColumn(name="activities_id")},
               inverseJoinColumns={@JoinColumn(name="Category_id")})
    private Category category;
}

public class Category {
    @OneToMany(mappedBy = "category") // inverse side: it has a mappedBy attribute, and can't decide how the association is mapped, since the other side already decided it.
    @Fetch(FetchMode.JOIN)
    @JsonIgnore
    private Collection<Activity> activities;
}

编辑:

此外,您的查询应该只选择活动,而不是查询加入的所有实体,方法是添加一个 select 子句:

select a from Activity as a where a.category.id= :categoryId order by a.key
于 2012-07-07T22:24:02.910 回答