JPA : Automatically fetch child object - java

I'm using #OneToMany feature, with FetchType.EAGER set. But JPA (through EclipseLink) keep making one sub request for each sub object in my list.
I really dont get why.
I follow many thread I found, but cant make this select work in one single request.
Also, I retrive my object with CriteriaBuilder, CriteriaQuery and some Predicate. This may be an issue ?
Anyway, all this filter are only use for the top lvl classes. I still want the lower one to be fetched as well.
My entities look like :
#Entity
#Table(name = "mainTable")
public class MainTable extends SqlEntity {
#OneToMany(fetch = FetchType.EAGER)
private List<MainLocation> locations = new ArrayList<MainLocation>();
...
}
#Entity
#Table(name = "mainLocation")
public class MainLocation extends SqlEntity {
#OneToMany(fetch = FetchType.EAGER)
private List<MainDetail> details = new ArrayList<MainDetail>();
...
}
#Entity
#Table(name = "mainDetail")
public class MainDetail extends SqlEntity {
...
}

Related

How do you map two abstract InheritanceType.TABLE_PER_CLASS entities with a OneToMany relationship?

I'm using Hibernate with Spring Boot and JPA, and have a business requirement to retrieve and combine in to a single paged response data that is stored in four different tables in the DB.
Let's call the first two tables "tblCredits", containing Credits, and "tblDebits", containing Debits. For our purposes, those two tables are IDENTICAL - same column names, same column types, same ID fields, everything. And my endpoint is supposed to be able to return a combined list of both Credits and Debits, with the ability to search/sort by any/all of the fields being returned, and with paging.
If I controlled that DB, I would simply merge the two tables in to a single table, or create a view or stored proc which did that for me, but this is a legacy DB used by other applications which I can't modify in any way, so that's not an option.
If I didn't have to sort and page, I could just create two completely independent entities, create a separate Spring Data JPA repository for each entity, query the two repositories separately, and then just combine the results in my own code. But paging the combined results especially would get very hairy, I don't want to have to implement the merged paging logic myself unless I absolutely have to. Ideally I should be able to get JPA to handle all of that for me out-of-the-box.
I have been able achieve this first step for these first two tables using an abstract class declared as an Entity with InheritanceType.TABLE_PER_CLASS, like this:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitEntity {
/* literally all my properties and ID and column mappings here
...
*/
}
And then two concrete classes which extend that abstract entity and simply specify the two different table mappings, have no class-specific properties or column mappings at all:
#Entity
#Table(name = "tblCredits")
public final class Credit extends AbstractCreditDebitEntity {
//Literally nothing inside this class
}
#Entity
#Table(name = "tblDebits")
public final class Debit extends AbstractCreditDebitEntity {
//Literally nothing inside this class
}
So far so good, this works great, I am able to create a Spring JPA Repository on the AbstractCreditDebitEntity entity, under the hood that generates a union query on the two tables, and I am able to get back records from both tables in a single query, with appropriate paging and sorting. (The performance issues around union queries don't concern me at the moment.)
However, where I'm getting tripped up is on the next step, when I incorporate the additional two tables. tblCredits has a one-to-many relationship to tblCreditLineItems, and tblDebits has a one-to-many relationship to tblDebitLineItems. Again, tblCreditLineItems and tblDebitLineItems are IDENTICAL tables, from our perspective - same column names, same column types, same ID fields, everything.
So I can follow the same pattern as before for those sub-entities:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitLineItemEntity {
/* literally all my properties and ID and column mappings here
...
*/
}
#Entity
#Table(name = "tblCreditLineItems")
public final class CreditLineItem extends AbstractCreditDebitLineItemEntity {
//Literally nothing inside this class
}
#Entity
#Table(name = "tblDebitLineItems")
public final class DebitLineItem extends AbstractCreditDebitLineItemEntity {
//Literally nothing inside this class
}
But now I need to create the mappings between the Credit/Debit entities and CreditLineItem/DebitLineItem entities. And this is where I'm struggling. Because I need to be able to filter which specific Credit/Debit entities I return based on the values of properties inside their associated CreditLineItem/DebitLineItem entities, I need a bidirectional mapping between the two entities, and I've been unable to get that working successfully.
Here's how far I've gotten so far. First the three Credit/Debit entities with the OneToMany mapping to their associated CreditLineItem/DebitLineItem entities:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitEntity {
/* literally all my properties and ID and column mappings here
...
*/
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName"
)
public abstract List<AbstractCreditDebitLineItemEntity> getCreditDebitLineItems();
public abstract void setCreditDebitLineItems(List<AbstractCreditDebitLineItemEntity> items);
}
#Entity
#Table(name = "tblCredits")
public final class Credit extends AbstractCreditDebitEntity {
private List<CreditLineItem> creditDebitLineItems;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = CreditLineItem.class)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName"
)
#Override
public List<AbstractCreditDebitLineItemEntity> getCreditDebitLineItems() {
return Optional.ofNullable(creditDebitLineItems).stream()
.flatMap(List::stream)
.filter(value -> AbstractCreditDebitLineItemEntity.class.isAssignableFrom(value.getClass()))
.map(AbstractCreditDebitLineItemEntity.class::cast)
.collect(Collectors.toList());
}
#Override
public void setCreditDebitLineItems(List<AbstractCreditDebitLineItemEntity> items) {
creditDebitLineItems = Optional.ofNullable(items).stream()
.flatMap(List::stream)
.filter(value -> CreditLineItem.class.isAssignableFrom(value.getClass()))
.map(CreditLineItem.class::cast)
.collect(Collectors.toList());
}
}
#Entity
#Table(name = "tblDebits")
public final class Debit extends AbstractCreditDebitEntity {
private List<DebitLineItem> creditDebitLineItems;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = DebitLineItem.class)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName"
)
#Override
public List<AbstractCreditDebitLineItemEntity> getCreditDebitLineItems() {
return Optional.ofNullable(creditDebitLineItems).stream()
.flatMap(List::stream)
.filter(value -> AbstractCreditDebitLineItemEntity.class.isAssignableFrom(value.getClass()))
.map(AbstractCreditDebitLineItemEntity.class::cast)
.collect(Collectors.toList());
}
#Override
public void setCreditDebitLineItems(List<AbstractCreditDebitLineItemEntity> items) {
creditDebitLineItems = Optional.ofNullable(items).stream()
.flatMap(List::stream)
.filter(value -> DebitLineItem.class.isAssignableFrom(value.getClass()))
.map(DebitLineItem.class::cast)
.collect(Collectors.toList());
}
}
And then the three CreditLineItem/DebitLineItem entities with their ManyToOne mappings back to the Credit/Debit entities:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitLineItemEntity {
/* literally all my properties and ID and column mappings here
...
*/
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName",
updatable = false,
insertable = false)
public abstract AbstractCreditDebitEntity getCreditDebit();
public abstract void setCreditDebit(AbstractCreditDebitEntity creditDebitEntity);
}
#Entity
#Table(name = "tblCreditLineItems")
public final class CreditLineItem extends AbstractCreditDebitLineItemEntity {
private Credit creditDebit;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName",
updatable = false,
insertable = false)
#Override
public Credit getCreditDebit() {
return creditDebit;
}
#Override
public void setCreditDebit(AbstractCreditDebitEntity creditDebitEntity) {
creditDebit =
Optional.ofNullable(creditDebitEntity)
.filter(value -> Credit.class.isAssignableFrom(value.getClass()))
.map(Credit.class::cast)
.orElse(throw new RuntimeException());
}
}
#Entity
#Table(name = "tblDebitLineItems")
public final class DebitLineItem extends AbstractCreditDebitLineItemEntity {
private Debit creditDebit;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName",
updatable = false,
insertable = false)
#Override
public Debit getCreditDebit() {
return creditDebit;
}
#Override
public void setCreditDebit(AbstractCreditDebitEntity creditDebitEntity) {
creditDebit =
Optional.ofNullable(creditDebitEntity)
.filter(value -> Debit.class.isAssignableFrom(value.getClass()))
.map(Debit.class::cast)
.orElse(throw new RuntimeException());
}
}
This code compiles, however... when in my automated tests I try to persist one of my Credit entities (I use a simple H2 database for my automated tests), I get the following error:
2021-04-02 13:53:52 [main] DEBUG org.hibernate.SQL T: S: - update AbstractCreditDebitLineItemEntity set MyIdColumnName=? where ID=?
2021-04-02 13:53:52 [main] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper T: S: - could not prepare statement [update AbstractCreditDebitLineItemEntity set MyIdColumnName=? where ID=?]
org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "ABSTRACTCREDITDEBITLINEITEMENTITY" does not exist
It appears to be trying to persist based on the #OneToMany mapping from my AbstractCreditDebitEntity class to my AbstractCreditDebitLineItemEntity. Which, since it's an abstract class with InheritanceType.TABLE_PER_CLASS, has no table specified for it, so it assumes the table it needs to persist to has the same name as the class.
What I wanted to happen here is for the #OneToMany mapping on the concrete getter in the Credit subclass, which specifies its targetEntity as the concrete CreditLineItem.class, to essentially override/replace the #OneToMany mapping on its parent abstract class. But it seems the mapping on the concrete class gets completely ignored?
I could remove the #OneToMany mapping from the AbstractCreditDebitEntity class entirely, and only define that mapping in the two concrete Credit/Debit entities that extend it. That makes the persistence error go away, and 90% of my test cases pass... but in that case when I try to filter or sort the results coming back from the combined AbstractCreditDebitEntity Spring Data JPA repository based on one of the fields that only exists in the CreditLineItem/DebitLineItem sub-entity, the query fails due to the AbstractCreditDebitEntity no longer having any mapping to the AbstractCreditDebitLineItemEntity.
Is there any good way of resolving this problem, so that the OneToMany mapping from AbstractCreditDebitEntity to AbstractCreditDebitLineItemEntity still exists, but the knowledge that the Credit entity maps specifically to the CreditLineItem entity and the Debit entity maps specifically to the DebitLineItem entity is also maintained?
After a lot of experimentation, I found something that works for me.
Basically, rather than try to override the OneToMany mapping in the abstract entity class with the OneToMany mappings in the concrete entities, I had to make them completely separate mappings to completely different properties. Which means my concrete entities have two different collections of AbstractCreditDebitLineItemEntity, and some AbstractCreditDebitLineItemEntity objects will appear twice, in both collections. A bit wasteful in terms of memory/computation, but I'm okay with that, it works!
So here's what I ended up with:
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitEntity {
/* literally all my properties and ID and column mappings here
...
*/
private List<AbstractCreditDebitLineItemEntity> creditDebitLineItems;
#OneToMany(fetch = FetchType.LAZY, targetEntity = AbstractCreditDebitLineItemEntity.class)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName",
updatable = false,
insertable = false
)
public List<AbstractCreditDebitLineItemEntity> getCreditDebitLineItems() {
return creditDebitLineItems;
}
public void setCreditDebitLineItems(List<AbstractCreditDebitLineItemEntity> items) {
creditDebitLineItems = items;
}
}
#Entity
#Table(name = "tblCredits")
public final class Credit extends AbstractCreditDebitEntity {
private List<CreditLineItem> creditLineItems;
#OneToMany(cascade = CascadeType.ALL, targetEntity = CreditLineItem.class)
#LazyCollection(LazyCollectionOption.FALSE)
#JoinColumn(
name = "MyIdColumnName",
referencedColumnName = "MyIdColumnName"
)
public List<CreditLineItem> getCreditLineItems() {
return creditLineItems;
}
#Override
public void setCreditDebitLineItems(List<CreditLineItem> items) {
creditLineItems = items;
}
}
With the exact same pattern repeated for the Debit entity.
This allows me to both:
persist, using the OneToMany mappings from the concrete Credit and Debit entities to the concrete CreditLineItem and DebitLineItem entities; and
do finds on the Spring Data JPA repository of AbstractCreditDebitEntity, using the the completely separate OneToMany mapping from that abstract entity to the AbstractCreditDebitLineItemEntity.
Not as clean as if I'd been able to override the OneToMany mapping in the abstract parent class with a more specific OneToMany mapping in the concrete child classes... but as I said, it works!
(The answer on this issue helped me know I needed to replace fetchType=FetchType.EAGER on my concrete OneToMany mappings with #LazyCollection(LazyCollectionOption.FALSE):
Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags)

Entity Merge using Cascade.ALL OnetoMany relationship not inserting records for children

I already looked at previous questions but all the solutions still doesn't work on my project.
I have a CUBA Platform project that uses spring core 5.2.3. CUBA uses the ORM implementation based on the EclipseLink framework.
I have 1 MainClass Entity, and children, SubClass Entity.
MainClass Definition
//annotations here
public class MainClass{
#Composition
#OnDelete(DeletePolicy.CASCADE)
#OneToMany(mappedBy = "mainClass", cascade = CascadeType.ALL, orphanRemoval = true)
protected List<SubClass> subClass;
public Category getCategory() {
return category;
}
}
//SubClass entity
//annotations here
public class SubClass{
#NotNull
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "MAINCLASS_ID")
protected MainClass mainClass;
}
The problem with this setup is that it only saves the MainClass Entity but not the SubClass Entity.
Service Class
#Service("MainService")
public class ServiceClass{
#Inject
private Persistence persistence;
#Transactional
public void saveOrUpdateMain(MainClass mainClass){
MainClass qMainClass = (MainClass) entityManager.createQuery("select
b from main_Class b where b.extID = ?1")
.setParameter(1, extID).getSingleResult();
//assume mainClass is not null, set the primary key of qMainClass to mainClass
mainClass.setId(qMainClass.getId());
entityManager.merge(mainClass);
}
}
I have read this 2 links but still did not solve my issue.
Why merging is not cascaded on a one to many relationship
JPA does not insert new childs from one to many relationship when we use merge
In CUBA, DataManager is a preferred option to work with data. It automatically resolves cascade operations and does not require explicit transaction definition. Please try to implement this logic using DataManager first.

Hibernate multi-module project: extend entity to add many-to-many relationship

I have a project that uses Hibernate and is divided into multiple modules.
I have the following modules:
device (defines entity Device)
appstore (defines entity Application)
device-appstore-integration (adds many-to-many relationship between Device and Application).
Entities look like this:
#Entity
#Table(name = "devices")
public class Device extends AbstractAuditingEntity implements Serializable
{
#NotNull
#EmbeddedId
private DeviceIdentity identity;
// ...
}
#Entity
#Table(name = "apps")
public class App extends AbstractAuditingEntity implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
// ...
}
Now I want device-appstore-integration module to add many-to-many relationship between the two entities above.
I thought about adding entity DeviceWithInstalledApps to define this many2many relationship and used the following code:
#Entity
#Table(name = "devices")
public class DeviceWithInstalledApps extends Device
{
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(
name = "devices_installed_apps",
joinColumns = {/*...*/},
inverseJoinColumns = {/*...*/}
)
private Set<App> installedApps = new HashSet<>();
// ...
}
The problem is that Hibernate requires devices table to include dtype column and treats DeviceWithInstalledApps as a separate entity that inherits from Device but I don't actually want it to be a separate entity. It's still the same entity, just with many-to-many relationship added so that I can actually access this relationship, no columns are added so there is no actual need to provide dtype column, it simply doesn't make sense in this context.
Is there any other way to define many-to-many relationship in JPA/Hibernate so that I can actually implement business logic without getting into issues mentioned above?

JPA Criteria API recursive fetch lazy association

I have a recursive entity which has an association with itself.
#Entity
public class Function {
(...)
#ManyToMany(fetch = FetchType.LAZY)
private Set<Function> children = new HashSet<>();
}
If this association would be eager #ManyToMany(fetch = FetchType.EAGER), then all of its children would always be initialized with one trip to the database. Of course, I don't want this association to be eager.
With the JPA Criteria API, one could fetch a collection with someRoot.fetch(Function_.children). This only fetches it one level deep though and is not recursive like the eager fetch type.
Is there a way to recursively fetch its children without making it an eager association?
I've opted to go for multiple mappings for the same table. There's some dangers in this, but since the entities are short lived and only one of them needs to be writable, it's fine.
In my case, one of them doesn't even need to access its children, further simplifying my this entity.
#MappedSuperclass
public class BaseFunction {
(...)
}
#Entity
#Table(name = "function")
public class RecursiveFunction extends BaseFunction {
#ManyToMany(fetch = FetchType.EAGER)
private Set<RecursiveFunction> children = new HashSet<>();
}
#Entity
#Table(name = "function")
public class SimpleFunction extends BaseFunction {}

Hibernate: Used mappedBy on class that extends another class annotated as JoinedSubclass?

The following doesn't work:
#Entity
class Owner {
#OneToMany(mappedBy="owner", cascade = {CascadeType.ALL})
protected Set<B> getBSet() {
..
}
}
#Entity
#Inheritance(strategy=InheritanceType.JOINED)
class A {
#ManyToOne
public Owner getOwner() {
...
}
}
#Entity
class B extends A {
}
It causes an exception as such:
org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: B.user in Owner.
I am trying to avoid copying the "owner" property into class B (which will consequently "denormalize" and copy the owner key into both tables generated for entity A and B). Also, I would really like to have A and B in a separate table and not have to use a discriminator by using SingleTable inheritance.
Also, I can't figure out how to do something similar by using #OneToOne between A and B (and not having B extend A).
It's a Hibernate oddity, but it's deliberate. I have a blog post up with background information, links and a workaround for the JOINED solution.
Try adding targetEntity = Transaction.class. This worked for me when I was using SINGLE_TABLE inheritance. I didn't try it with JOIN.
#Entity
class Owner {
#OneToMany(mappedBy="owner", cascade = {CascadeType.ALL}, targetEntity = Transaction.class)
#Where(clause = "tableType='I'")
protected Set<B> getBSet() {
..
}
}
I'd double check your real implementation. I used your sample code and after adding an #Id everything worked as expected. Even IntelliJ says getBSet() is associated with B.owner.

Categories

Resources