正确使用实体管理器 Find() 方法

Correct using of Entity manager Find() method

我在使用 EntityManager 从数据库中获取数据时遇到问题 这是我的用户实体

@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

我尝试使用用户名搜索用户:

public User findByUserName(String username){
    return entityManager.find(User.class, username);
}

但是有错误

Provided id of the wrong type for class project.model.User. Expected: class java.lang.Integer, got class java.lang.String

正确的使用方法是什么? 我如何检查 table 中的用户名 uniuqe?

您必须为您的目的创建一个 查询 - find 仅适用于主键(顺便说一句, find知道您在示例中要查找的属性吗?):

User user = entityManager.createQuery(
  "SELECT u from User u WHERE u.username = :username", User.class).
  setParameter("username", username).getSingleResult();

要确保列是唯一的,只需将 unique 添加到您的列定义中:

@Column(name = "username", unique = true, length = 20, nullable = false)
private String username;