Hibernate @Enumerated seems to be ignored

≡放荡痞女 提交于 2019-12-11 04:12:38

问题


I have the class Person mapped with annotations with enum Sex reffering to the sex if is male or female. Let's see:

@Entity
@Table(name = "PERSON")
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Enumerated(EnumType.STRING)
    @Column(name = "SEX")
    private Sex sex;

    private enum Sex {
        M,
        F;
    } 

    // Getters, setters & constructors
}

When I test getting all the rows from the MySQL database, it works and the mapping is correct.

The database is already predefined, here is the column's definition:

`SEX` enum('M','F') NOT NULL

However the error occurs when I configure Hibernate with hibernate.hbm2ddl.auto=validate:

found [enum (Types#CHAR)], but expecting [varchar(255) (Types#VARCHAR)]

The error is a bit different (expecting [integer (Types#INTEGER)]) happend when I use EnumType.ORDINAL or no @Enumerated at all.

What do I do wrong?


回答1:


try add columnDefinition

@Enumerated(EnumType.STRING)
@Column(name = "SEX" , columnDefinition="ENUM('M','S')" ,nullable = false )
private Sex sex;

hibernate validate do check types , lenght.... as you have this in db level validator thinks it's different type .

I didn't see it with Oracle , but with MySql it's might be



来源:https://stackoverflow.com/questions/44864675/hibernate-enumerated-seems-to-be-ignored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!