gpt4 book ai didi

java - 我无法将列表项插入对象

转载 作者:行者123 更新时间:2023-11-30 10:54:19 25 4
gpt4 key购买 nike

我想将列表项插入对象,这是代码:

public User login(String username, String password) {
String stringQuery = "SELECT * FROM User U WHERE U.username = :username AND U.password = :password";
Query query = HibernateUtil.getCurrentSession().createSQLQuery(stringQuery);
query.setParameter("username", username);
query.setParameter("password", password);

User user;

List<User> userList = query.list();

if (userList.size() == 0){
return null;
}

user = (User) userList.get(0);

return user;
}

这里是 User.class

@Entity
public class User {
private int id;
private String username;
private String password;

@Id
@Column(name = "id")
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

@Basic
@Column(name = "username")
public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

@Basic
@Column(name = "password")
public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

User user = (User) o;

if (id != user.id) return false;
if (password != null ? !password.equals(user.password) : user.password != null) return false;
if (username != null ? !username.equals(user.username) : user.username != null) return false;

return true;
}

@Override
public int hashCode() {
int result = id;
result = 31 * result + (username != null ? username.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
}
}

在这一行我得到了错误:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to org.project.server.base.User

user = (User) userList.get(0);

最佳答案

根据documentation , 使用 addEntity :

Query query = HibernateUtil.getCurrentSession().createSQLQuery(stringQuery);
query.addEntity(User.class);

关于java - 我无法将列表项插入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33719936/

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