Search code examples
hibernatejpaembeddedhibernate-mappingoption-type

How to mark a relation optional using EmbeddedId?


I have an entity which should join another entity. This relation is optional and uses an EmbeddedId.

@ManyToOne
@JoinColumns({
    @JoinColumn(name = "CUST_NR", referencedColumnName = "CUST_NR", insertable = false, updatable = false),
    @JoinColumn(name = "BILL_NR", referencedColumnName = "BILL_NR", insertable = false, updatable = false)})
@ForeignKey(name = "none")
// Field is optional, so no need for a constraint
// Need to use deprecated annotation https://hibernate.atlassian.net/browse/HHH-8805
private Report report;

If I query the entity which has no related report it fails with

javax.persistence.EntityNotFoundException: Unable to find Report with id ReportPk@62675cdb

It is working for simple IDs. What did I miss?

A working workaround would using FetchType.LAZY. But I want to try to avoid it.


Solution

  • There is no possibility in JPA itself. If you want to use hibernate specific annotations, you can use the NotFound annotation.

    @ManyToOne
    @JoinColumns({
        @JoinColumn(name = "CUST_NR", referencedColumnName = "CUST_NR",
                    insertable = false, updatable = false),
        @JoinColumn(name = "BILL_NR", referencedColumnName = "BILL_NR", 
                    insertable = false, updatable = false)})
    @ForeignKey(name = "none")
    // Field is optional, so no need for a constraint
    // Need to use deprecated annotation https://hibernate.atlassian.net/browse/HHH-8805
    @NotFound(NotFoundAction.IGNORE)
    private Report report;
    

    Have a look to @NotFound(NotFoundAction.IGNORE).