使用批注或hbm.xml文件执行JPA或Hibernate枚举映射有多难? 实际上一点也不难。 实际上,您不必执行任何映射,因为Hibernate的默认设置将为您处理大多数底层细节。
JPA和Hibernate枚举映射
Java 5中引入的Java枚举无需任何干预即可映射到基础数据库。 JPA框架(无论是Hibernate还是Toplink或DataNucleus)将识别Java枚举,并随后往返于该枚举状态。 因此,在hbm.xml文件中不需要任何其他注释或编码。
每当我需要证明一个概念时,我总是喜欢编写一个剪刀石头布的程序 。 在此用例中,我们可以将竞争对手在游戏中选择的手势表示为Java枚举:
package com.mcnz.rps;
public enum Gesture {
ROCK, PAPER, SCISSORS;
}
使用持久性实体
只要问题域中的任何持久对象都具有必需的@Entity和@Id属性,Java枚举数据库映射就将继续进行而不会出现错误。 以下是使用名为Gesture的Java枚举的JPA注释实体:
/* JPA & Hibernate enum mapping example */
package com.mcnz.rps;
import javax.persistence.*;
@Entity
public class GameSummary {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private Gesture clientGesture;
private Gesture serverGesture;
private String result;
private java.util.Date date = new java.util.Date();
public GameSummary(){}
public GameSummary(Gesture clientGesture, Gesture serverGesture) {
super();
this.clientGesture = clientGesture;
this.serverGesture = serverGesture;
}
}
/* End of Hibernate and JPA enum mapping example */
JPA和Java枚举持久性
现在我们已经创建了Java枚举并对JPA或Hibernate实体进行了编码,我们需要做的就是给予JPA EntityManager或Hibernate Session一定的关注,并且数据库持久性应该是一个引导管道。
/* Entity that has a JPA/Hiberante mapped enum */
GameSummary gs = new GameSummary();
gs.clientGesture = Gesture.PAPER;
gs.serverGesture = Gesture.ROCK;
gs.result = "win";
/* Persisting the JPA/Hiberate mapped enum */
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-enum-mapping");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(gs);
em.getTransaction().commit();
Java枚举和EnumType批注
但是,这种Hibernate枚举映射方法在最后一刻令人惊讶。 与实际的String相反,Java枚举的序数被写入数据库。 因此,ROCK手势保持为0 ,而PAPER手势保持为1 。
为了使JPA或Hibernate枚举映射过程将文本而不是序号写入数据库,技巧是将@Enumerated批注与@EnumType结合使用。
@Enumerated(EnumType.STRING)
private Gesture clientGesture;
@Enumerated(EnumType.STRING)
private Gesture serverGesture;
使用@Enumerated和@EnumType批注进行映射
在将EnumType设置为STRING而不是ORDINAL的情况下,JPA和Hibernate枚举映射使用特定文本而不是枚举的序数值表示Java枚举。
当然,所有这些映射都使用了JPA。 所有概念都直接映射到Hibernate ,尽管语法略有不同,特别是如果您使用hbm.xml文件进行枚举映射。 XML如下所示:
<property name="gesture" column="GESTURE">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">com.mcnz.rps.Gesture</param>
<param name="useNamed">true</param>
</type>
</property>
如果没有useName参数-或如果useName参数设置为false-则使用表示枚举的序数值,否则枚举的String表示形式将持久化到数据库中。
就是这样。 这些就是使用Hibernate和JPA枚举映射功能的来龙去脉。