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

jah*_*hra 4 hibernate entitymanager

我在使用 EntityManager Here my User 实体从数据库中获取数据时遇到问题

@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
Run Code Online (Sandbox Code Playgroud)

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

public User findByUserName(String username){
    return entityManager.find(User.class, username);
}
Run Code Online (Sandbox Code Playgroud)

但是有错误

Provided id of the wrong type for class project.model.User. Expected: class java.lang.Integer, got class java.lang.String
Run Code Online (Sandbox Code Playgroud)

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

Tob*_*fke 8

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

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

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

@Column(name = "username", unique = true, length = 20, nullable = false)
private String username;
Run Code Online (Sandbox Code Playgroud)