hibernate enum映射详解

hibernate enum映射详解

在这里介绍注解的形式,如果想要了解XML配置的方式,可以自行查找相关资料。

例如以下Entity

@Entity
@Table(name = "t_user")
public class User implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = -9042615274714038279L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "password")
    private String password;

    @Column(name = "age")
    private Integer age;

    @Column(name = "gender")
    //@Convert(converter = Genderconverter.class) //属性类型转换器,该配置映射到数据库后是自定的类型,例如保存性别是保存M/F,男/女
    //@Enumerated(EnumType.ORDINAL) //该配置映射保存到数据库后保存的是序号,从0开始
    //@Enumerated(EnumType.STRING) //该配置映射保存到数据后保存的String类型,例如MALE/FEMALE等
    private Gender gender;
    
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
    
    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "User[id=" + id + ", name=" + name + ",age=" + age + ", gender=" + gender + "]";
    }
}

Gender

/**
 * 性别
 * @author daniel.zhao
 *
 */
public enum Gender {
    
    MALE("M"),
    FEMALE("F");
    
    private String code;
    
    private Gender(String code) {
        this.code = code;
    }
    
    public String getCode() {
        return code;
    }
    
    public void setCode(String code) {
        this.code = code;
    }
    
    public static Gender fromString(String code) {
        Objects.requireNonNull(code, "Gender code must not be null!");
        if (Gender.MALE.code.equals(code)) {
            return Gender.MALE;
        }
        if (Gender.FEMALE.code.equals(code)) {
            return Gender.FEMALE;
        }
        return null;
    }
}

GenderConverter

@Converter
public class Genderconverter implements AttributeConverter<Gender, String> {

    @Override
    public String convertToDatabaseColumn(Gender attribute) {
        return attribute.getCode();
    }

    @Override
    public Gender convertToEntityAttribute(String dbData) {
        return Gender.fromString(dbData);
    }

}

使用以上方法可以映射保存对应的枚举类型到数据表中。

posted @ 2017-03-17 22:36  低调的小黑  阅读(1957)  评论(0编辑  收藏  举报