janssen-dev
janssen-dev

Reputation: 2771

Spring Data JPA / Hibernate - findByY(String y) method in @Repository where Y is accessible via object X

I've got a UserRepository:

@Repository
public interface UserRepository extends JpaRepository<User, Long>
{
}

where User:

@Entity
@Table(name = 'user')
public class User
{
    @Id
    private Long id;

    @OneToOne(mappedBy = "owner", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private UserDetails userDetails;
}

and UserDetails:

@Entity
@Table(name = 'user_details')
public class UserDetails
{
    @Id
    private Long id;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private User owner;

    private String name;
}

Packages, imports, getters and setters are excluded for cleaner code.


Now, how can I find users by their name? Adding this to the UserRepository interface will not work:

List<User> findByName(String name);

because it throws:

No property name found for type User

I am looking for something like this:

List<User> findByNameOfUserDetails(String name);

Upvotes: 0

Views: 296

Answers (1)

Arnold Galovics
Arnold Galovics

Reputation: 3416

Please take a look at the Spring Data JPA docs here.

You'll need something like findByUserDetailsName(String name). To resolve this ambiguity you can use _ inside your method name to manually define traversal points. So our method name would be findByUserDetails_Name(String name).

Upvotes: 2

Related Questions