org.hibernate.WrongClassException on saving an entity via Hibernate

后端 未结 2 1638
一整个雨季
一整个雨季 2021-01-23 02:58

In this question I am working with Hibernate 4.3.4.Final and Spring ORM 4.1.2.RELEASE.

I have an User class, that holds a Set of CardInstances like this:



        
2条回答
  •  心在旅途
    2021-01-23 03:36

    I solved the problem.

    The root cause lies in this design:

    @Table
    @Entity
    @Inheritance
    @DiscriminatorColumn(name = "card_type", discriminatorType = DiscriminatorType.STRING)
    public class CardInstance {  
        protected T card;
    }
    
    @Entity
    @DiscriminatorValue("leader")
    public class LeaderCardInstance extends CardInstance {
    }
    

    At runtime information about generic types of an class are not present in java. Refer to this question for further information: Java generics - type erasure - when and what happens

    This means hibernate has no way of determining the actual type of the CardInstance class.


    The solution to this is simply getting rid of the generic type and all extending (implementing) classes and just use one class like this:

    @Table
    @Entity
    @Inheritance
    @DiscriminatorColumn(name = "card_type", discriminatorType = DiscriminatorType.STRING)
    public class CardInstance {
        Card card;
    }
    

    This is possible (and by the way the better design) because the member card carries all the information about the card type.


    I hope this helps folk if they run into the same problem.

提交回复
热议问题