TheLordOne
TheLordOne

Reputation: 65

Find by object attribute spring data

I have two class :

  1. -->User(id/username(string)/password(string))
  2. -->Role(id/role(string)/user(User))

    @Entity
    @Table(name="Utilisateur")
    public class User {
      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      private long id;
      private String username;
      private String password;
    } 
    
    @Entity                 
    public class Role {    
      @Id
      @GeneratedValue(strategy=GenerationType.IDENTITY)
      private long id;
      private String role;
    
      @ManyToOne
      @JoinColumn(name="user_id")
      private User user ;
    }
    

how to write a function in RoleRepository that find Role by username in user

I try List<Role> findByUsername(String username) but not work !

Upvotes: 0

Views: 100

Answers (1)

fkrsc
fkrsc

Reputation: 151

You can't write findByUsername in RoleRepository. There is no username property for Role. The following functions solve the problem.

public interface RoleRepository extends CrudRepository<Role, Long> {
    List<Role> findRoleByUser_Username(String username);
    List<Role> findByUser_Username(String username);
}

Upvotes: 2

Related Questions