gpt4 book ai didi

java - 如何防止 JPA 实体出现 ClassCastException?

转载 作者:太空宇宙 更新时间:2023-11-04 13:32:28 24 4
gpt4 key购买 nike

尝试查询 JPA 实体类时出现 ClassCastException。我只希望 json 显示两列。那就是姓名和地址。如何在 JPA 中仅显示选定的列?从调试来看,肯定是for循环。所以 List 是对象,我需要将右侧设置为对象而不是列表,正确吗?

实体

@Entity
@Table(name = "Personnel")
public class User implements Serializable {

private String id;
private String name;
private String address;

public User(String id, String name, String address)
{
this.id = id;
this.name = name;
this.address = address;
}

@Id
@Column(name = "name", unique = true, nullable = false)
public String getName() {
return this.name;
}....
//setters getters

查询/实现

public List<User> getRecords(User ent){

String sql = "select "
+ " usr.name, usr.address "
+ " from User usr"
+ " where usr.id = '1' ";

List<User> records = this.getSession().createQuery(sql).list();
for ( User event : records ) {
System.out.println( "Records (" + event.getName + ") );
}

return records;
}

更新

这是我尝试将结果对象声明为 List。该方法是否必须是对象而不是?

public List<User> getRecords(User ent){
String sql = "select "
+ " usr.name, usr.address "
+ " from User usr"
+ " where usr.id = '1' ";

Map<String, String> results = new HashMap<String, String>();
List<Object[]> resultList = this.getSession().createQuery(sql).list();

// Place results in map
for (Object[] items: resultList) {
results.put((String)items[0], (String)items[1]);
results.toString();
}
return (List<User>) results;

最佳答案

您可以将 DTO 类传递给 SELECT 子句,如下所示:

List<UserDTO> resultList = this.getSession().createQuery("""
select
new my.package.UserDTO(usr.name, usr.address)
from User usr
where usr.id = :userId
""")
.setParameter("userId", userId)
.getResultList();

关于java - 如何防止 JPA 实体出现 ClassCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32034490/

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