Hibernate enum Mapping detailed
Here we introduce the form of annotations, and if you want to understand how XML is configured, you can find the relevant data yourself.
For example, the following entity
@Entity @table (name= "T_user") Public classUserImplementsSerializable {/** * */ Private Static Final LongSerialversionuid = -9042615274714038279l; @Id @GeneratedValue (Strategy=Generationtype.auto)PrivateLong ID; @Column (Name= "Name") PrivateString name; @Column (Name= "Password") PrivateString password; @Column (Name= "Age") PrivateInteger age; @Column (Name= "Gender")//@Convert (Converter= Genderconverter.class)//attribute type converter, which is mapped to a database after a custom type, such as Save gender is saved m/f, male/female//@Enumerated (enumtype.ordinal)//The configuration map is saved to the database after the ordinal, starting from 0//@ enumerated (enumtype.string)//This configuration maps the type of STRING saved after saving to the data, such as Male/female, etc.PrivateGender Gender; PublicLong getId () {returnID; } Public voidsetId (Long id) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name = Name = =NULL?NULL: Name.trim (); } PublicString GetPassword () {returnpassword; } Public voidSetPassword (String password) { This. Password = Password = =NULL?NULL: Password.trim (); } PublicInteger getage () {returnAge ; } Public voidsetage (Integer age) { This. Age =Age ; } PublicGender Getgender () {returngender; } Public voidSetgender (Gender Gender) { This. Gender =gender; } @Override PublicString toString () {return"user[id=" + ID + ", name=" + name + ", age=" + Age + ", gender=" + Gender + "]"; }}
Gender
/*** Gender *@authorDaniel.zhao **/ Public enumGender {MALE (M), FEMALE (F); PrivateString Code; PrivateGender (String code) { This. Code =Code; } PublicString GetCode () {returnCode; } Public voidSetcode (String code) { This. Code =Code; } Public StaticGender fromstring (String code) {objects.requirenonnull (code,"Gender code must not being null!"); if(Gender.MALE.code.equals (code)) {returnGender.male; } if(Gender.FEMALE.code.equals (code)) {returnGender.female; } return NULL; }}
Genderconverter
@Converter Public class Implements Attributeconverter<gender, string> { @Override public String Converttodatabasecolumn (Gender attribute) { return attribute.getcode (); } @Override public Gender converttoentityattribute (String dbdata) { return gender.fromstring (dbdata);} }
Using the above method, you can map and save the corresponding enumeration type to the data table.
Hibernate enum Mapping detailed