Kiran S
Kiran S

Reputation: 88

ClassCastException while retrieving list from database using Hibernate

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

this is my Entity class ,

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

when i run this method, it doesn't return me a List<FoodItem> instead it returns a List<Array> like this,

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

and if i try to set the restaurant object to null in each object in the list,

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

i got ClassCastException. i need the response in key : value pair as per my entity class can anyone solve this for me. thanks. [update] Solved!

Upvotes: 0

Views: 486

Answers (2)

J-Alex
J-Alex

Reputation: 7107

NativeQuery has a bounded type parameter. Use it and pass expected resultClass as a second parameter for a proper generic resolution and you'll get an expected result.

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;

Upvotes: 0

shakhawat
shakhawat

Reputation: 2727

You suppose to get list of object array from the native query. It will not construct type objects out of the box for you. If you want typed list, you need to do JPQL instead of native query.

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

Iterate over the list and construct the typed object list -

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

  }

Upvotes: 1

Related Questions