在這裏介紹註解的形式,若是想要了解XML配置的方式,能夠自行查找相關資料。數據庫
例如如下Entityide
@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 + "]"; } }
Genderui
/** * 性別 * @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; } }
GenderConverterthis
@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); } }
使用以上方法能夠映射保存對應的枚舉類型到數據表中。spa