Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

java - Enum in Hibernate, persisting as an enum

In my MySQL database, there's the column "gender enum('male','female')"

I've created my enum "com.mydomain.myapp.enums.Gender", and in my Person entity I'm defined "Gender gender".

Now I'd want to keep the enum type in my MySQL database, but when I launch my application I get:

Wrong column type in MyApp.Person for column Gender. Found: enum, expected: integer

Why is this? This would be the equivalent as if I'd annotated my "Gender gender" with "@Enumerated(EnumType.ORDINAL)", which I haven't. EnumType seems only to be able to be either ORDINAL or STRING, so how do I specify that it should treat the field as an enum, not as an int? (not that there's much difference, but enough for it to get upset about it.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My understanding is that MySQL enum type is very proprietary and not well supported by Hibernate, see this comment from Gavin King (this related issue is a bit different but that's not the important part).

So, I actually think that you'll have to use your own UsereType and I'd recommend to use the Flexible solution - working version from the Java 5 EnumUserType (see Appfuse's Java 5 Enums Persistence with Hibernate for an example).

Personally, I'd just forget the idea to use MySQL enum, I'm not convinced that the "benefits" are worth it (see this answer for more details).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...