Search code examples
hibernatejoinnamed-queryspring-repositories

Method query with multiple tables including ordering?


I'm not sure if I hit the boundaries of the method query with this task. I have two tables, a User table and a Password table. A User may have multiple Passwords (Where as the newest one is the current).

I would like to make a method query in my User repository to fetch a "current" Password for a user name.

In SQL it would look something like this

"Select FIRST(*) from Passwords INNERJOIN Users ON Users.id=Passwords.userId WHERE Users.username=%s ORDER BY Passwords.created DESC"

What I have tried as method query is findFirstPasswordOrderByPasswords_CreatedByUsers_Username(String username)

which gives me an exception:

No property byUsers found for type long! Traversed path: UsersEntity.passwords.created.

I don't know why it is still pointing to the created field. Is this too much for method queries? Or am I doing it simply wrong?


Solution

  • You should define this method in Password repository as you are searching for password. In that repository this method will look like:

    Passwords findFirstByUser_UsernameOrderByCreatedDesc(String username);
    

    To implement this method, your Password entity class should have reference to Users table on User property(from the query)