使用Hibernate从数据库检索列表时发生ClassCastException

时间:2019-01-14 08:52:35

标签: 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(name="status")
private String status;

@Column(name="image")
private String image;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "RestaurantId", nullable = false)
private Restaurant restaurant;

这是我的Entity类,

public List<FoodItem> getFoodItems(Restaurant restaurant) {
    Session session=getSession();
    List<FoodItem> list=null;
    NativeQuery<?> query = session.createNativeQuery("SELECT " + 
            "   \"Item\"," + 
            "   \"ItemName\"," + 
            "   \"ItemPrice\"," + 
            "   \"RestaurantId\"," + 
            "   \"status\"," + 
            "   \"image\" " + 
            "FROM \"SYSTEM\".\"FoodItem\" where \"RestaurantId\"="+restaurant.getRestaurantId());
    list = (List<FoodItem>) query.getResultList();
    return  list;
}

当我运行此方法时,它不会返回List<FoodItem>,而是返回List<Array>

[
[
    1,
    "Pasta",
    55,
    14,
    "Veg",
    null
],
[
    2,
    "Burger",
    35,
    14,
    "Veg",
    null
]
]

如果我尝试将列表中每个对象中的restaurant对象设置为null,

for(int index=0 ;index< list.size();index++)
        list.get(index).setRestaurant(null);

我得到了ClassCastException。 我需要根据我的实体类在key:值对中进行响应 谁能为我解决这个问题。 谢谢。 [更新]解决了!

2 个答案:

答案 0 :(得分:1)

您假设要从本机查询中获取对象数组的列表。它不会为您开箱即用地构造类型对象。如果要输入列表,则需要执行JPQL而不是本机查询。

List<Object[]> listResults = query.getResultList();

遍历列表并构建类型化的对象列表-

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);

  }

答案 1 :(得分:0)

NativeQuery有一个有界类型参数。使用它并将期望的resultClass用作适当的通用分辨率的第二个参数,您将获得期望的结果。

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;