目录
- 概述
- 演示环境
- 示例
[一]、概述
本文主要是结合实际代码详细演示Hibernate对JPA实现的应用示例。
[二]、演示环境
- Hibernate 4.2.1.Final
- Java 1.7.0_25
- Maven 3.0.4
[三]、示例
1.创建演示项目
1 |
mvn archetype:generate -DgroupId=com.micmiu -DartifactId=hibernate-jpa-demo -Dversion=1.0-SNAPSHOT -DpackageName=com.micmiu.hibernate.jpa -Dpackage=com.micmiu.hibernate -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false |
创建好项目后,以Maven Project导入Eclipse,配置相关的builder path,截图如下:
配置修改 pom.xml 文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.micmiu</groupId> <artifactId>hibernate-jpa-demo</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>hibernate-jpa-demo</name> <description>hibernate jpa</description> <url>http://www.micmiu.com</url> <organization> <name>micmiu.com</name> <url>http://www.micmiu.com</url> </organization> <developers> <developer> <id>Michael</id> <name>Michael Sun</name> <email>sjsky007@gmail.com</email> <url>http://www.micmiu.com</url> <timezone>+8</timezone> <roles> <role>architect</role> <role>developer</role> </roles> </developer> </developers> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <jdk.version>1.6</jdk.version> <hibernate.version>4.2.1.Final</hibernate.version> <log4j.version>1.2.16</log4j.version> <slf4j.version>1.6.4</slf4j.version> <junit.version>4.11</junit.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.3.0</version> </dependency> <!-- logger begin --> <!-- slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <!-- slf4j-log4j绑定 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- common-logging 调用 slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- Logging end --> </dependencies> </project> |
2.创建一个测试的Entity类:
UserInfo.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
package com.micmiu.hibernate.jpa; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * * @author <a href="http://www.micmiu.com">Michael</a> * @time Create on 2013-9-17 下午11:27:06 * @version 1.0 */ @Entity @Table(name = "T_DEMO_USER_INFO") public class UserInfo implements Serializable { private static final long serialVersionUID = 4943396187256597131L; @Id @GeneratedValue @Column(name = "ID") private Integer id; @Column(name = "USER_NAME", length = 20) private String userName; @Column(name = "EMAIL", length = 64) private String email; @Column(name = "BLOG_URL", length = 64) private String blogURL; public Integer getId() { return id; } public String getUserName() { return userName; } public String getEmail() { return email; } public String getBlogURL() { return blogURL; } public void setId(Integer id) { this.id = id; } public void setUserName(String userName) { this.userName = userName; } public void setEmail(String email) { this.email = email; } public void setBlogURL(String blogURL) { this.blogURL = blogURL; } @Override public String toString() { return "UserInfo [id=" + id + ", userName=" + userName + ", email=" + email + ", blogURL=" + blogURL + "]"; } } |
3.创建配置文件:
META-INF/persistence.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <!-- 为持久化单元取名为 myJPA --> <persistence-unit name="myJPA" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <!-- class 定义指定持久化的实体类 注意配置属性hibernate.archive.autodetection=false --> <!-- <class>com.micmiu.hibernate.jpa.UserInfo</class> --> <properties> <property name="hibernate.archive.autodetection" value="class,hbm"/> <!--配置Hibernate方言 --> <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" /> <!--配置数据库url --> <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:orcl" /> <!--配置数据库驱动 --> <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" /> <!--配置数据库用户名 --> <property name="hibernate.connection.username" value="micmiu" /> <!--配置数据库密码 --> <property name="hibernate.connection.password" value="111111" /> <!--设置外连接抓取树的最大深度 --> <property name="hibernate.max_fetch_depth" value="3" /> <!--自动输出schema创建DDL语句 --> <property name="hibernate.hbm2ddl.auto" value="update" /> </properties> </persistence-unit> </persistence> |
4.创建测试类
EntityManagerTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
package com.micmiu.hibernate; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.micmiu.hibernate.jpa.UserInfo; /** * 单元测试 * * @author <a href="http://www.micmiu.com">Michael</a> * @time Create on 2013-9-20 下午11:23:32 * @version 1.0 */ @SuppressWarnings("unchecked") public class EntityManagerTest { AtomicInteger atom = new AtomicInteger(); EntityManagerFactory emf = null; @Before public void before() { // 根据persistence.xml中配置创建EntityManagerFactory emf = Persistence.createEntityManagerFactory("myJPA"); } @After public void after() { if (null != emf) { emf.close(); } } @Test public void testCreate() { System.out.println(">>>> testCreate <<<<"); int beforeCount = queryList(); System.out.println(">>>> before create count = " + beforeCount); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); UserInfo user = generateRadomEntity(); em.persist(user); em.getTransaction().commit(); em.close(); int afterCount = queryList(); System.out.println(">>>> after create count = " + afterCount); Assert.assertEquals(beforeCount + 1, afterCount); } @Test public void testRead() { System.out.println(">>>> testRead <<<<"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); UserInfo user = em.find(UserInfo.class, 1); if (null != user) { Assert.assertEquals(1, (long) user.getId()); System.out.println(">>>> find user = " + user); } else { System.out.println(">>>> find use not exit."); } em.getTransaction().commit(); em.close(); } /** * 更新操作- 用于托管状态的对象 */ @Test public void testUpdate() { System.out.println(">>>> testUpdate <<<<"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); UserInfo user = em.find(UserInfo.class, 1); System.out.println(user); user.setEmail("micmiu.com@gmail.com"); em.getTransaction().commit(); em.close(); UserInfo user2 = findUser(1); System.out.println(user2); Assert.assertEquals("micmiu.com@gmail.com", user2.getEmail()); } /** * 更新操作 - 用于游离(脱管)状态的对象 */ @Test public void testMerge() { System.out.println(">>>> testMerge <<<<"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); UserInfo user = em.find(UserInfo.class, 1); System.out.println(user); // 将实体管理器中的所有实体变成了游离态(脱管) em.clear(); user.setEmail("michael@micmiu.com"); em.merge(user); em.getTransaction().commit(); em.close(); UserInfo user2 = findUser(1); System.out.println(user2); Assert.assertEquals("michael@micmiu.com", user2.getEmail()); } @Test public void testDelete() { System.out.println(">>>> testDelete <<<<"); int beforeCount = queryList(); System.out.println(">>>> before delete count = " + beforeCount); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); UserInfo user = em.find(UserInfo.class, 2); em.remove(user); em.getTransaction().commit(); em.close(); int afterCount = queryList(); System.out.println(">>>> after delete count = " + afterCount); Assert.assertEquals(beforeCount - 1, afterCount); } private UserInfo findUser(Integer id) { EntityManager em = emf.createEntityManager(); UserInfo user = em.find(UserInfo.class, id); em.close(); return user; } private int queryList() { EntityManager em = emf.createEntityManager(); List<UserInfo> list = (List<UserInfo>) em.createQuery( "select t from UserInfo t order by t.userName").getResultList(); em.close(); return list.size(); } /** * @param args */ public static void main(String[] args) { } private UserInfo generateRadomEntity() { UserInfo user = new UserInfo(); String key = atom.addAndGet(1) + ""; user.setUserName("michael-" + key); user.setEmail(key + "@micmiu.com"); user.setBlogURL("micmiu.com"); return user; } } |
5.初始化数据:
1 2 |
INSERT INTO T_DEMO_USER_INFO(ID,BLOG_URL,EMAIL,USER_NAME) VALUES (1, 'micmiu.com', 'sjsky007@gmail.com', 'michael'); INSERT INTO T_DEMO_USER_INFO(ID,BLOG_URL,EMAIL,USER_NAME) VALUES (2, 'ctosun.com', 'admin@ctosun.com', 'michael'); |
运行单元测试类全部通过,日志如下:
>>>> testMerge <<<<
UserInfo [id=1, userName=michael, email=sjsky007@gmail.com, blogURL=micmiu.com]
UserInfo [id=1, userName=michael, email=michael@micmiu.com, blogURL=micmiu.com]
>>>> testRead <<<<
>>>> find user = UserInfo [id=1, userName=michael, email=michael@micmiu.com, blogURL=micmiu.com]
>>>> testCreate <<<<
>>>> before create count = 2
>>>> after create count = 3
>>>> testDelete <<<<
>>>> before delete count = 3
>>>> after delete count = 2
>>>> testUpdate <<<<
UserInfo [id=1, userName=michael, email=michael@micmiu.com, blogURL=micmiu.com]
UserInfo [id=1, userName=michael, email=micmiu.com@gmail.com, blogURL=micmiu.com]
本文介绍到此结束@Michael Sun.
原创文章,转载请注明: 转载自micmiu – 软件开发+生活点滴[ http://www.micmiu.com/ ]
本文链接地址: http://www.micmiu.com/j2ee/hibernate/hibernate-jpa-demo/
0 条评论。