get updated row in one to many mapping using hibernate

可紊 提交于 2019-12-24 16:53:21

问题


I have two entities Issue and Issue_Tracker. I have joined both table in an one to many mapping. In Issue_Tracker , We can have multiple entries like

  issue_id  tracker_status      tracked_time
    123     Assigned           1/8/2013 11:44
    123     Assigned           1/8/2013 11:45
    123     Completed          1/8/2013 11:52
    32      Assigned           1/9/2013 16:46
    33      Assigned           1/9/2013 16:47
    33      Cancel             1/9/2013 16:49 

I want to Order the Issue_tracker entity by tracked_time so I can get only last update tracker_status.I am using criteria to get data,However I am getting first entry for example : for issue_id 123, I get tracker_status as Assigned , But I want to fetch tracker_status : Completed for id 123. How to achieve this. My DAO is as follows

     Criteria criteria = session.createCriteria(Issue.class);
     criteria.setFirstResult(from);
     criteria.setMaxResults(size);
     criteria.setFetchMode("Issue.issueTracker",FetchMode.JOIN);
     criteria.add(Restrictions.eq("status", "Escalate To"));
      return criteria.list();

Issue.java

public class Issue implements Serializable
        {
        private Integer issue_id;
        private String  issue_description;
        private Date issue_raised_date;
        private Set<Issue_Tracker> issueTracker = new HashSet<Issue_Tracker>(0);



        @OneToMany(fetch=FetchType.LAZY, mappedBy="issue_id")
        public Set<Issue_Tracker> getIssueTracker() {
        return issueTracker;
    }

        public void setIssueTracker(Set<Issue_Tracker> issueTracker) {
        this.issueTracker = issueTracker;

Issue_Tracker.java

public class Issue_Tracker implements Serializable
{  
     private Integer   issue_id;
     private String    tracker_status;
     private Timestamp tracked_time;

I hope you guys can get what i am trying to ask, any help?


回答1:


Add an @OrderBy annotation to the mapped collection. This should return the entities in the set ordered by the tracked time. The first entity in the set should be the latest.

//Issue.java
    @OneToMany(fetch=FetchType.LAZY, mappedBy="issue_id")
    @OrderBy("tracked_time DESC")
    public Set<Issue_Tracker> getIssueTracker() {
    return issueTracker;

You may also want to try:

 Criteria criteria = session.createCriteria(Issue.class);
 criteria.setFirstResult(from);
 criteria.setMaxResults(size);
 criteria.setFetchMode("Issue.issueTracker",FetchMode.JOIN);
 criteria.add(Restrictions.eq("status", "Escalate To"));
 Criteria subCriteria = criteria.createCriteria("issueTracker");
 subCriteria.addOrder(Order.desc("tracked_time"));
 return criteria.list();


来源:https://stackoverflow.com/questions/14255493/get-updated-row-in-one-to-many-mapping-using-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!