问题
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