Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JPA query couldn't find the right constructor

So basically I try to get some data of a User by its ID and it has a field with @OneToOne relationship(bidirectional)

When I try to create a query in JpaRepository
with @Query annotation

@Query("SELECT new com.project.model.user(u.id, u.username, u.profile.last_online, u.profile.about) FROM User u WHERE id = :id)

and a constructor

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

User(long id, long username, Profile profile) {
   this.id = id;
   this.username = username;
   this.profile = profile;
}

it still can’t really find the constructor and says that there is no "matching constructor", is there a way to create the constructor better?

>Solution :

The constructor you expect in your query has (long, String, Timestamp, String). And your constructor takes (long, long, Profile).

So you need to create a matching constructor:

public User(long id, String username, Timestamp lastOnline, String about) {
    this.id = id;
    this.username = username;
    this.profile = new Profile(lastOnline, about); // create new Profile with lastOnline & about
}

This should work.

But may I ask why you’re not using the JpaRepository#findById(Long id) method?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading