Search code examples
hibernatejpahibernate-mapping

How can i make a @resultsetmapping for a @onetomany only happen if the foreign key is not null?


I have a class with a one-to-many association:

public class Location {
......
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, fetch = FetchType.LAZY)
@JoinColumn(name = "ledgerId")
@JsonIgnore
protected LedgerValue ledgerValue;

The fetching is complex, so i have a nativequery with a resultsetmapping for the LedgerValue, like this:

@ConstructorResult(
        targetClass = LedgerValue.class,
        columns = {
            @ColumnResult(name = "lvid"),
            @ColumnResult(name = "mainc", type = Long.class),
            @ColumnResult(name = "emailonly", type = Boolean.class),
            @ColumnResult(name = "copy", type = Boolean.class),
        }
    )

This all works, my Location class gets populated with a LedgerValue entity. However, in the cases where there is no LedgerValue associated with a Location, i still get a LedgerValue object with only null values.

I would, rather, that the LedgerValue object itself is null. I have looked around but haven't been able to find a way to do this, except for doing the entire sql myself, or a ResultSetExtractor.

I there a (hopefully simplish) way to accomplish this?

Pointers appreciated.


Solution

  • I ended up using my native SQL in combination with a SQLResultSetMapping and a ResultTransformer.