Java 使用Hibernate从数据库检索列表时发生ClassCastException
这是我的实体类Java 使用Hibernate从数据库检索列表时发生ClassCastException,java,spring,hibernate,rest,Java,Spring,Hibernate,Rest,这是我的实体类 @Id @Column(name="Item", unique = true, nullable = false) @GeneratedValue(strategy=GenerationType.IDENTITY) private int itemId; @Column(name="ItemName") private String itemName; @Column(name="ItemPrice") private double itemPrice; @Column(n
@Id
@Column(name="Item", unique = true, nullable = false)
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int itemId;
@Column(name="ItemName")
private String itemName;
@Column(name="ItemPrice")
private double itemPrice;
@Column(name="status")
private String status;
@Column(name="image")
private String image;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "RestaurantId", nullable = false)
private Restaurant restaurant;
如果我试图在列表中的每个对象中将restaurant对象设置为null
[
[
1,
"Pasta",
55,
14,
"Veg",
null
],
[
2,
"Burger",
35,
14,
"Veg",
null
]
]
for(int index=0;index
我有个例外。
我需要根据我的实体类在key:value对中进行响应
谁能帮我解决这个问题。
谢谢
[更新]已解决 您应该从本机查询中获取对象数组的列表。它不会为您构造开箱即用的类型对象。如果您想要类型化列表,您需要执行
JPQL
而不是本机查询
for(int index=0 ;index< list.size();index++)
list.get(index).setRestaurant(null);
List listResults=query.getResultList();
迭代列表并构造类型化对象列表-
List<Object[]> listResults = query.getResultList();
List foodItems=new ArrayList();
对于(对象[]记录:listResults){
FoodItem=新的FoodItem();
//从记录中设置值,并执行必要的强制转换。
添加(项目);
}
NativeQuery
有一个有界类型参数。使用它并将expectedresultClass
作为第二个参数传递给适当的通用解析,您将得到预期的结果
List<FoodItem> foodItems = new ArrayList();
for (Object[] record : listResults) {
FoodItem item = new FoodItem();
// set values from record, do necessary casts as well.
foodItems.add(item);
}
NativeQuery=session.createNativeQuery(“选择”+
“\”项目\“,“+
“\”项目名称“,“+
“\”项目价格\“,“+
“\”餐厅\“,“+
“\”状态\“,“+
“\”图像“+”
“来自\“系统\”“FoodItem\”,其中\“RestaurantId\”=“+restaurant.getRestaurantId(),
食品类);
List=query.getResultList();
退货清单;
您正在尝试使用本机查询获取对象列表。我想删除本机查询将起作用。您正在获取的记录的格式仍然是元组,抛出异常[Request processing failed;嵌套异常为java.lang.ClassCastException:[Ljava.lang.Object;无法转换为com.xxx.foodorder.entity.FoodItem(由org.apache.catalina.loader加载)。ParallelWebappClassLoader@0x00000001003006e8)]使用根本原因java.lang.ClassCastException:[Ljava.lang.Object;无法强制转换为com.xxx.foodorder.entity.FoodItem(由org.apache.catalina.loader加载)。ParallelWebappClassLoader@0x00000001003006e8)这很有效,我将了解JPQL方法。谢谢。
List<FoodItem> foodItems = new ArrayList();
for (Object[] record : listResults) {
FoodItem item = new FoodItem();
// set values from record, do necessary casts as well.
foodItems.add(item);
}
NativeQuery<FoodItem> query = session.createNativeQuery("SELECT " +
" \"Item\"," +
" \"ItemName\"," +
" \"ItemPrice\"," +
" \"RestaurantId\"," +
" \"status\"," +
" \"image\" " +
"FROM \"SYSTEM\".\"FoodItem\" where \"RestaurantId\"="+restaurant.getRestaurantId(),
FoodItem.class);
List<FoodItem> list = query.getResultList();
return list;