许多到一与表一起处于休眠资源类使用新泽西州JAX-RS(Many-To-One with join

2019-06-26 03:33发布

我使用的泽西实现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":""}}]

我很欣赏的任何帮助。

Answer 1:

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

双向关联总是有一个业主方(其中指定连接列或连接表的使用,以及反侧它说的帽子它的另一面使用的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 a from Activity as a where a.category.id= :categoryId order by a.key


文章来源: Many-To-One with join Table in hibernate resource classes for a JAX-RS using Jersey