org.hibernate.WrongClassException on saving an entity via Hibernate

后端 未结 2 1639
一整个雨季
一整个雨季 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-23 03:29

    According to the first paragraph of the JavaDocs for @ManyToOne:

    It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced.

    However, in this case, @ManyToOne is on a field whose type is generic and generic type information gets erased at the type of compilation. Therefore, when deserializing, Hibernate does not know the exact type of the field.

    The fix is to add targetEntity=Card.class to @ManyToOne. Since Card is abstract and has @Inheritance and @DiscriminatorColumn annotations, this forces Hibernate to resolve the actual field type by all possible means. It uses the discriminator value of the Card table to do this and generates the correct class instance. Plus, type safety is retained in the Java code.


    So, in general, whenever there is the chance of a field's type not being known fully at runtime, use targetEntity with @ManyToOne and @OneToMany.

提交回复
热议问题