Get last post from @OneToMany relationship

I have a couple of objects with @ManyToOne and @OneToMany relationships, and the fact is that I'm looking for a way to get the last record inserted from the @OneToMany relationship side without loading all the entries from list, Actually, I keep this last record in the relationship @OneToOne in ClassB, but this creates too many conflicts with FK restrictions. Here is an excerpt from how it looks:

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

, ClassA ClassB, ClassB , ClassA ( ClassA), ClassA , . - lastClassA, ClassA .

JPQL, classAList ( ), , . , - ?

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

All Articles