Sviatlana
Sviatlana

Reputation: 1888

REST web service returns more than one entity in JSON

I am using REST web service. I am trying to get one entity from the database, but my method returns a lot of same records. I am using EclipseLink JPA implementation.

Here is my entity:

@Entity
@Table(name = "News")
public final class News implements Serializable, IEntity {

/**
 * For deserialization with no exception after modification.
 */
private static final long serialVersionUID = 3773281197317274020L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "news_id", precision = 0)
private Long newsId; // Primary key

@Column(name = "title")
private String title;

@Column(name = "short_text")
private String shortText;

@Column(name = "full_text")
private String fullText;

@Temporal(TemporalType.DATE)
@Column(name = "creation_date")
private Date creationDate;

@Temporal(TemporalType.DATE)
@Column(name = "modification_date")
private Date modificationDate;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "news")
private List<Comment> commentsList;

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "news_tag", joinColumns = { @JoinColumn(name = "news_id") }, inverseJoinColumns = { @JoinColumn(name = "tag_id") })
private Set<Tag> tagSet;

@ManyToOne(fetch = FetchType.EAGER)
@JoinTable(name = "news_author", joinColumns = { @JoinColumn(name = "news_id") }, inverseJoinColumns = { @JoinColumn(name = "author_id") })
private Author author;

My controller method:

@RequestMapping(value = { "/singleNews/{newsId}" }, method = RequestMethod.GET)
public @ResponseBody News showSingleNews(@PathVariable("newsId") Long newsId) throws ServiceException {
    News news = newsService.getSingleNewsById(newsId);
    news.setCommentsList(commentService.getListOfCommentsByNewsId(newsId));
    return news;
}

Upvotes: 1

Views: 138

Answers (2)

Nicolas Zozol
Nicolas Zozol

Reputation: 7038

Your code is typed-protected : you can only receive one News. This news may have many Comments, and I suppose it's not a problem, and a even good idea to fetch them all eagerly.

My first idea is that you must have fetch the wrong route, or have ambiguous routes.

Upvotes: 1

Mohamed Nabli
Mohamed Nabli

Reputation: 1649

try to use fetch type lazy for each list you have in your class

@OneToMany(fetch = FetchType.LAZY)

Upvotes: 1

Related Questions