使用JPA,MVC-JSP + Servlets,JSTL
实体和重要财产:
@Entity
public class Post {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "post_id", unique = true, nullable = false)
private Integer id;
@OneToMany(cascade = { ALL }, fetch = EAGER, mappedBy = "post")
private Set<Comment> comments = new HashSet<Comment>();
//...
}
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "comment_id", unique = true, nullable = false)
private Integer id;
@Column(name = "comment_date", unique = false, nullable = false)
private Date date;
@ManyToOne
@JoinColumn (name = "post_id", referencedColumnName="post_id", nullable = false)
private Post post;
//...
}
现在,在servlet的doGet
方法中,我有以下代码摘录:
Post post = null;
int postId = Integer.parseInt(request.getParameter("postId"));
post = postDao.findById(postId);
request.setAttribute("post", post);
RequestDispatcher dispatcher = request.getRequestDispatcher("post.jsp");
dispatcher.forward(request, response);
在JSP
页面中:
<c:if test="${fn:length(post.comments)>0}">
<section id="postComments">
<strong>Comments:</strong>
<c:forEach items="${post.comments}" var="comment">
<div class="postComment">
<div class="commentInfo"><strong>${comment.user.name}</strong> says:</div>
<br>
<div class="commentTitle">${comment.title}</div>
<hr>
<div>${comment.content}</div>
</div>
</c:forEach>
</section>
</c:if>
这样我就收到了帖子的所有评论,但我希望按照date
属性对它们进行排序。我知道Set
不是有序集合,那么如何阅读这些注释以使它们按date
属性排序?
答案 0 :(得分:2)
您可以使用@OrderBy
注释JPA关系,LinkedHashSet
将使用提供的字段以指定的顺序从数据库中检索实体。同时将set实现更改为@OneToMany(cascade = { ALL }, fetch = EAGER, mappedBy = "post")
@OrderBy("date DESC")
private Set<Comment> comments = new LinkedHashSet<Comment>();
以保留数据库中的顺序。
@OrderBy
有关详细信息,您可以观看我创建的video tutorial,其中说明了如何使用{{1}}。