Skip to content
Advertisement

Translate SQL into Hibernate HQL

I’m using Spring boot along with Hibernate. I’ve only recently started using Java so I’m not quite good at it.

I have a OneToMany unidirectional relationship with a join table.

RssUrl Table

JavaScript

User Table

JavaScript

Join table

JavaScript

I’m trying to translate this SQL into HQL

JavaScript

It’s basically checking if a url is already associated with a user. I’m sure it’s not the most efficient sql out there but it gets the job done(I’m more than happy to hear how I can improve it, but that’s besides the point).

So far I got this going for me, which is really not a lot tbh.

JavaScript

I’ve also considered alternative methods, such as letting the database error out and catching the exception but that’ just seems wrong.

This question has 2 parts:

  • What is the correct HQL for the above query?

  • Is there an easier way to do this? I come from a PHP background. Using ORMs like Doctrine made things a lot easier. One could in fact fetch related entities with considerably less hassle. I find it hard to believe that Hibernate doesn’t have a better way to do this.

I’d love to google it myself but quite frankly I don’t know what to google exactly.

Advertisement

Answer

In actual, java jpa is not friendly with join table query; in there, I can give you two methed only for refer:

  1. you can split this query into three base query to complete you question, i know this method is not good;
  2. you can define an entity as a join entity, then use @OneToOne or @ManyToOne anaotations to reflect the relation;
  3. I aslo has the 3 suggestion, not use jpa but use mybatis, in mybatis, you can direct use your sql lile what you write when query with many table;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement