java - REST Web 服务以 JSON 格式返回多个实体

标签 java json rest jpa

我正在使用 REST Web 服务。我正在尝试从数据库中获取一个实体,但我的方法返回许多相同的记录。我正在使用 EclipseLink JPA 实现。

这是我的实体:

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

我的 Controller 方法:

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

最佳答案

尝试对类(class)中的每个列表使用惰性获取类型

@OneToMany(fetch = FetchType.LAZY)

关于java - REST Web 服务以 JSON 格式返回多个实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33893017/

相关文章:

java - SimpleDateFormat - 日、月、时间不正确

JavaFX:如何在新场景中更新 observableArrayList 中选定的项目。没有传递整组数据支持吗?

java - 我无法生成正确的代码来选择我正在处理的 BI 仪表板上的特定过滤器

c# - 从嵌套的 JSON 中检索字符串 - System.Collections.Generic.List`1[System.String]

java - 在从 jQuery ajax 调用的 Spring REST Controller 中解析请求 JSON

java - 如何计算半径内的最大和最小纬度和经度值?

javascript - JSON 数组 - 删除第一个元素

json - 我在 Swift 5 上解码 json 时出错

wordpress - 如何获取 woocommerce 的所有产品?

java - JAX-RS — 如何同时返回 JSON 和 HTTP 状态码?