gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:26:33 24 4
gpt4 key购买 nike

我在使用 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

什么是方法的正确使用?
我如何检查表中的用户名 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;

关于hibernate - 实体管理器 Find() 方法的正确使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31725401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com