Get last record from @OneToMany relationship

安稳与你 提交于 2019-12-23 12:47:53

问题


I have a couple of entities with a @ManyToOne and @OneToMany relationships, and the thing is that I am looking for a way to get the last record inserted from the @OneToMany side of the relationship without loading all the records from the list, Actually, I am saving this last record in a @OneToOne relationship in ClassB, but that creates too many conflicts with FK constraints. Here is an extract of how it looks like:

public class ClassA {
   @Id
   public Long id;
   @ManyToOne
   public ClassB classB;
   @Temporal(javax.persistence.TemporalType.TIMESTAMP)
   public Date startDate;
}

public class ClassB {
   @Id
   public Long id;
   @OneToMany(mappedby = "classB", fetch = FetchType.LAZY)
   public List<ClassA> classAList = new ArrayList<>();
   @OneToOne
   public ClassA lastClassA; // Generates a bidirectional FK, and unable the entity for deletion.
}

The interaction between these classes is that ClassA is accumulated over time and is saved linked to ClassB, at the time of ClassB do some work, it only needs the last ClassA instance created (which would be the current ClassA), the previous instances of ClassA are not important since they are in the past now, and are only kept for history. So, because of this I created the field lastClassA which is updated every time a new ClassA is created and saved on disk.

I could also create a JPQL to get this last Record from the classAList field (demo bellow), but I am not sure that is the best way to do it. So, does anybody know about a strategy to get this last record without loading the entire list and selecting the last member of the list?

Select a from ClassA a where a.startDate = (Select MAX(b.startDate) from ClassA b where ClassB.id=:classBId)

来源:https://stackoverflow.com/questions/21222735/get-last-record-from-onetomany-relationship

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