Mrfk
Mrfk

Reputation: 15

Spring boot jpa, composition - how to find an object with a property from another class

I'm trying to write an basic registration/login module for my app with Spring boot JPA. The problem is that I'm using a composition:

public class Person {

    private int personID;
    private String name;
    private String email;
    private String password;
    
    // Constructors, getters and setters ommited for brevity
}


public class User {
    
    private int buyerID;
    
    @ManyToOne
    @NotNull
    private Person person;
    
    // Other fields, getters and setters ommited for brevity
    
}

Now I want to find an User by email. I have repositories interfaces extending JpaRepository and:

public interface PersonRepository extends JpaRepository<Person, Integer> {

    Person findByEmail(String email);

}

Of course there can be only one Person associated with the User. I cannot figure out how to find out which User is connected with which email address.

Upvotes: 0

Views: 377

Answers (1)

hakima maarouf
hakima maarouf

Reputation: 2280

Please try something like this .. I supposed that the person refrence in user table is called id_person, otherwise you put the right names

 @Query(value = "SELECT DISTINCT p.* from person p inner join user u on p.id=u.id_person where u.email = ?1", nativeQuery = true)
 Person findByEmail(String email);

Upvotes: 1

Related Questions