I am using a RESTful web service using Jersey. I am using hibernate to communicate with a database (mySQL). My hibernation resource classes include:
@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;
}
and class 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;
}
I used this query to get attributes:
session.createQuery("from Activity a join a.category cs where cs.id= :categoryId order by a.key").setLong("categoryId", categoryId).list();
The result in JSON format is incorrect:
[[{"id":26,"key":"other","name":"Other","cost":100.0,"category":{"id":10,"name":"General","description":""}},{"id":10,"name":"General","description":""}]]
As you can see, the category is printed 2 times, and we have an extra [] around it. When I use another one-to-many relationship mechanism in a category class, for example:
@OneToMany(targetEntity = Activity.class, mappedBy = "category", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonIgnore
private Collection<Project> activities;
And in the Activity class:
@ManyToOne(optional = false)
private Category category;
And this request:
session.createQuery("from Activity as a where a.category.id= :categoryId order by a.key").setLong("categoryId", categoryId).list();
Everything works perfectly. But I need to use the connection table because I cannot change the database.
The correct result should look like this:
[{"id":26,"key":"other","name":"Other","cost":100.0,"category":{"id":10,"name":"General","description":""}}]
I appreciate any help.