Home > Back-end >  JPA query couldn't find the right constructor
JPA query couldn't find the right constructor

Time:07-12

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

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?

CodePudding user response:

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?

  • Related