0

I am new to HQL and trying to write a query that involves two entities. This is legacy code and adding the @OneToOne relationship to the FirstEntity would be a gigantic task.

On the other hand, I can change the firstEntityReference to have the @OneToOne.

@Entity
public FirstEntity {
    private long firstEntityId;
    ...
}

And second entity:

@Entity
public SecondEntity {
    private long secondEntityId;
    /*
     * I could Change this to:
     * @OneToOne
     * private FirstEntity firstEntityReference;
     * But not sure if it would help with anything
    */
    private long firstEntityReference;
    private boolean deleted;
    ...
}

The question is would it be possible to do something like this query:

select fe.* from FirstEntity fe
left join SecondEntity se on fe.firstEntityId = se.firstEntityReference
where (se is null or se.deleted = 1)

Keep in mind that the root of the query has to be FirstEntity. I am trying to wrap my head around whether the join is possible here: Join<FirstEntity, SecondEntity> join = ... but can't figure it out yet.

2 Answers2

1

A similar question that in my understanding covers your problem is How to join unrelated entities with the JPA Criteria API. Unfortunately it is not marked as resolved, but I consider Vlad Mihalceas answer as the one, you might want to follow.

EDIT The linked question gives plenty of options: Current Hibernate, NativeQuery or JOOQ. If they all not for you for whatever reason, your approach might just work as well. You should, however, keep in mind, that you have real OneToOne semantics ensured, meaning, that each SecondEntity belongs to exactly one or zero FirstEntities and that the firstEntityReference is unique, otherwise you might run into unexpected behaviour. Maybe also the ManyToOne mapping could be more appropriate, depending on your situation, I do not know your db design? If you can't touch the legacy db to add real constraints, you might also want to tell hibernate about it. Take a look at the Cocktail class here https://www.baeldung.com/jpa-query-unrelated-entities

Marius Schmidt
  • 633
  • 6
  • 18
1

Like I wrote in the other question, you can only make use of that through the Criteria API when using Blaze-Persistence: https://stackoverflow.com/a/58037766/412446

Other than that, you can only use HQL. In fact, the query you wrote should work.

Christian Beikov
  • 15,141
  • 2
  • 32
  • 58