轉載地址:http://my.oschina.net/u/1765238/blog/303425
1.首先導入jar包放入lib目錄下:
1
2
3
4
5
6
7
8
9
10
|
hibernate3.jar lib\jpa\hibernate-jpa- 2.0 -api- 1.0 . 0 .Final.jar lib\required\antlr- 2.7 . 6 .jar lib\required\commons-collections- 3.1 .jar lib\required\dom4j- 1.6 . 1 .jar lib\required\javassist- 3.12 . 0 .GA.jar lib\required\jta- 1.1 .jar lib\required\slf4j-api- 1.6 . 1 .jar 另外,還需要你用到的數據庫的JDBC驅動程序包。本文用的是Mysql,因此還有一個mysql-connector-java- 5.1 . 12 -bin.jar。 |
2.新建配置文件 persistence.xml:
1
|
src下必須有一個META-INF文件夾,而且persistence.xml必須在其內,文件名必須相同 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<? xml version = "1.0" encoding = "UTF-8" ?> < persistence 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" version = "2.0" > < persistence-unit name = "chenyue" transaction-type = "RESOURCE_LOCAL" > <!-- <jta-data-source>java:/DefaultDS</jta-data-source> --> < properties > < property name = "hibernate.dialect" value = "org.hibernate.dialect.MySQL5Dialect" /> < property name = "hibernate.hbm2ddl.auto" value = "update" /> < property name = "hibernate.connection.driver_class" value = "com.mysql.jdbc.Driver" /> < property name = "hibernate.connection.username" value = "root" /> < property name = "hibernate.connection.password" value = "123" /> < property name = "hibernate.connection.url" value = "jdbc:mysql://localhost:3306/chydb?useUnicode=true&characterEncoding=UTF-8" /> </ properties > </ persistence-unit > </ persistence > |
3.新建基本類用來測試:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package com.itcast.bean.product; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity
//標註其是一個實體bean public class ProductType { private Integer typeid; @Id
//對象標示符 @GeneratedValue (strategy=GenerationType.AUTO)
//數據庫中採用主鍵自增長 public Integer getTypeid() { return typeid; } public void setTypeid(Integer typeid) { this .typeid = typeid; } } |
4.用JUnit單元來測試:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package junit.test; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.junit.BeforeClass; import org.junit.Test; public class ProductTest { @BeforeClass public static void setUpBeforeClass(){ System.out.println( "setUpBeforeClass" ); } @Test public void jpaTest(){ EntityManagerFactory factory= Persistence.createEntityManagerFactory( "itcast" ); System.out.println(factory.toString()); } } |