【问题标题】:Correct using of Entity manager Find() method正确使用实体管理器 Find() 方法
【发布时间】:2015-07-30 13:40:37
【问题描述】:

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

【问题讨论】:

    标签: hibernate entitymanager


    【解决方案1】:

    您必须为您的目的创建一个 查询 - 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 2015-09-29
      • 2012-05-05
      • 2017-05-31
      • 2018-09-06
      相关资源
      最近更新 更多