如何使用JPA注解映射枚举类型

发表于: java/j2ee | 作者: | 日期: 2012/5/16 02:05

从JDK5.0开始,Sun引进了一个全新的关键字 enum 来定义一个枚举类型,于是 JPA 中也有相应的注解来对枚举类型进行映射。

假设顾客表如下:


CREATE TABLE `customer` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`state` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ak_key_2` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

相应的实体类如下:


@Entity
@Table(name = “CUSTOMER”, uniqueConstraints = @UniqueConstraint(columnNames = “name”))
public class Customer extends AuditableEntity {

private String name;//顾客名称
private StateEnum state;//状态

@Column(name = “name”, unique = true, length = 100)
public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

@Column(name = “state”, length = 10)
@Enumerated(EnumType.STRING)
public StateEnum getState() {
return state;
}

public void setState(StateEnum state) {
this.state = state;
}

public static enum StateEnum {
NORMAL, DELETE;
public String getLabel() {
switch (this) {
case NORMAL:
return “正常”;
case DELETE:
return “删除”;
}
return super.toString();
}
}
}

说明:

EnumType有两个值,ORDINAL表示持久化的为枚举类型的值,STRING表示持久化的为枚举类型的名称。

@Enumerated注解的API文档说明:

http://docs.oracle.com/javaee/5/api/javax/persistence/Enumerated.html

EnumType注解的API文档说明:

http://docs.oracle.com/javaee/5/api/javax/persistence/EnumType.html

参考文档:

http://blog.csdn.net/EJB_JPA/article/details/2422684

: https://blog.darkmi.com/2012/05/16/2301.html

本文相关评论 - 1条评论都没有呢
Post a comment now » 本文目前不可评论

No comments yet.

Sorry, the comment form is closed at this time.