EJB3 / JPA with aggregated attribute

I wanted to know if there is a way to relate one relationship between One2Many field on one side, which is the collection of Many.

Take the following example:

@Entity
public class A {
 @Id
 private Long id;
 @OneToMany (mappedBy="parentA")
 private Collection<B> allBs;

 // Here I don't know how to Map the latest B by date
 private B latestB;
    // Acceptable would be to have : private Date latestBDate;
}

@Entity
public class B {
 @Id
 private Long id;
 private Date date;
 @ManyToOne (targetEntity=A.class)
 private A parentA;
}

My question is, how can I make the lastB field display in entity object A without any de-normalization (without synchronizing the field with triggers / listeners)?

This question may give some answers, but I don’t really understand how it can work, since I still want to be able to retrieve all the child objects.

Thanks for reading / help.

PS: hibernate ORM/JPA, Hibernate , JPA .
PS2: , ( , ); -)

+3
2

hibernate ORM/JPA, Hibernate , JPA .

(, Date B) @Formula.

@Entity
public class A {
    @Id
    private Long id;
    @OneToMany (mappedBy="parentA")
    private Collection<B> allBs;

    @Formula("(select max(b.some_date) from B b where b.a_id = id)")
    private Date latestBDate;
}

+1
+2

Source: https://habr.com/ru/post/1764681/


All Articles