0

I have been trying to use an enumerator as a model field that would be saved as an integer in database, but the casting fails in Hibernate. I have installed the hibernate-core and hibernate-jpa-2.1-api maven packages.

I have a Bug.hbm.xml file, where I have set these fields as int

        <property name="state" column="State" type="int" />
    <property name="status" column="Status" type="int" />

Example model:

package Model;

// Class for the bug-object.

import javax.persistence.*;
import java.util.Date;

@Entity
public class Bug {
    private int id;

    @Enumerated(EnumType.ORDINAL)
    private BugState state;
    
    public Bug() {
    }
    
}

The enum

package Model;

public enum BugState {
    OPEN, CLOSED
}

The error

Caused by: java.lang.ClassCastException: class Model.BugState cannot be cast to class java.lang.Integer (Model.BugState is in module com.example.application of loader 'app'; java.lang.Integer is in module java.base of loader 'bootstrap')

Any help would be appreciated since I am new with Java and Hibernate!! It's difficult

1 Answers1

0

Ok so from:

        <property name="state" column="State" type="int">
            <type name="org.hibernate.type.EnumType">
                <param name="enumClass">Model.BugState</param>
            </type>
        </property>
        <property name="status" column="Status" type="int">
            <type name="org.hibernate.type.EnumType">
                <param name="enumClass">Model.Status</param>
            </type>
        </property>

I removed the type="int" from each property, and it started working. I did not realize this overrides the enumType.

Like this

        <property name="state" column="State">
            <type name="org.hibernate.type.EnumType">
                <param name="enumClass">Model.BugState</param>
            </type>
        </property>
        <property name="status" column="Status">
            <type name="org.hibernate.type.EnumType">
                <param name="enumClass">Model.Status</param>
            </type>
        </property>