Issue
Hello everyone hope you are safe with all what is happening right now. I'm struggling with spring data jpa no property found exception
the error is that spring cannot find the users when i run the application :
UsersRepository.findByName(java.lang.String)! No property name found for type Users!
here is my code:
this is my users.java
that contains all the fiels for the database
@Entity
@Table(name = "user")
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private int id;
@Column(name = "login")
private String userName;
@Column(name = "password")
private String password;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
public Users() {
}
public Users(Users users){
this.id=users.getId();
this.userName=users.getUserName();
this.password=users.getPassword();
this.roles=users.getRoles();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() { return userName; }
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
this is my UsersRepository.java
@Repository
public interface UsersRepository extends JpaRepository<Users, Integer> {
Optional<Users> findByName(String userName);
}
And finally this is MyUsersDetailsService.java
@Service
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UsersRepository usersRepository;
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
Optional<Users> optionalUsers = usersRepository.findByName(userName);
optionalUsers
.orElseThrow(() -> new UsernameNotFoundException(userName+"Utilisateur Introuvable!"));
return optionalUsers
.map(MyUserDetails::new).get();
}
}
Solution
Change your repository method name to
Optional<Users> findByUserName(String userName);
as you do not have property called name
.
Couple of suggestions:
- Keep your entity class name as
User
instead ofUsers
. (The entity class represents one record in the table which is basically anUser
) - Let the variable
userName
beusername
. (if you go with this, then the repository method name wouldfindByUsername
.
Answered By - vins