Reputation: 1235
I have a problem with fetching data from database using EntityManager Here my User entity
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonProperty
private Integer id;
@Column(name = "username", length = 20, nullable = false)
@JsonProperty
private String username;
@Column(name = "password", nullable = false, unique = true)
@JsonProperty
private String password;
@Column(name = "enabled", nullable = false)
@JsonProperty
private boolean enabled;
@Column(name = "email", nullable = false, unique = true)
@JsonProperty
private String email;
@OneToMany(mappedBy = "user", cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
private Set<UserRole> userRoles;
//getters and setters
I try to search user by username using:
public User findByUserName(String username){
return entityManager.find(User.class, username);
}
But have error
Provided id of the wrong type for class project.model.User. Expected: class java.lang.Integer, got class java.lang.String
What is the correct using of method? And how can I check is the username uniuqe in the table?
Upvotes: 4
Views: 10683
Reputation: 9022
You will have to create a query for your purpose - find
is only suitable for the primary key (by the way, how should find
know the attribute that you are looking for in your example?):
User user = entityManager.createQuery(
"SELECT u from User u WHERE u.username = :username", User.class).
setParameter("username", username).getSingleResult();
To ensure that a Column is unique just add unique
to your column definition:
@Column(name = "username", unique = true, length = 20, nullable = false)
private String username;
Upvotes: 10