Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct using of Entity manager Find() method

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?

like image 770
jahra Avatar asked Feb 09 '23 10:02

jahra


1 Answers

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;
like image 173
Tobias Liefke Avatar answered Feb 13 '23 03:02

Tobias Liefke