简体   繁体   中英

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;
}

尝试对班级中的每个列表都使用fetch type lazy

@OneToMany(fetch = FetchType.LAZY)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM