tr_quest
tr_quest

Reputation: 765

Cannot cast enum to String while persisting Object in hibernate

I am trying to persist my menuItem Object in the database. One of the itemFields is an ItemType string which is bounded by ItemType enum. Here is my MenuItem POJO.

public class MenuItemImpl implements MenuItem{

    private long id;

    private String itemName;

    private String itemType;

    private int itemPrice;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName= itemName;
    }

    public ItemType getItemType() {
        return ItemType.valueOf(itemType);
    }

    public void setItemType(ItemType itemType) {
        this.itemType=itemType.toString();
    }

    public int getItemPrice() {
        return this.itemPrice;
    }

    public void setItemPrice(int itemPrice) {
        this.itemPrice=itemPrice;
    }

}

This is my ItemType enum

public enum ItemType {
    BURGER("BURGER"), BEVERAGE("BEVERAGE"), SNACK("SNACK"), TOY("TOY");

    private String value;

    private ItemType(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return value;
    }
}

Now when I try to do a save on this object. I get the following exception:

    com.saggezza.ItemType cannot be cast to java.lang.String

I dont see why it should even try casting ItemType. as my getter and setter methods in the menuItem POJO already take care of the conversion of enum to string and string to enum.

Any ideas?

Upvotes: 1

Views: 4474

Answers (2)

Florent Bayle
Florent Bayle

Reputation: 11910

The problem is that Hibernate is using your getters/setters to access your property, so when it wants to get the value of the itemType field to save it, it will call getItemType(), expecting it to return a String (what is in the mapping), and will get an ItemType instead, thus the exception.

You can have a look at this answer to see how you can add your enum to your mapping directly.

Upvotes: 2

Alvin Bunk
Alvin Bunk

Reputation: 7764

I notice in this method:

public void setItemType(ItemType itemType) {
    this.itemType=itemType.toString();
}

You have the parameters specified as itemType and the global String variable itemType with the same name, to make it easier to support your code (and figure out where the error is occurring) I would suggest renaming the parameter to item. So like this:

public void setItemType(ItemType item) {
    this.itemType=item.toString();
}

Then you always know what item refers to.

Upvotes: -1

Related Questions