首页 > 代码库 > JPA环境的配置

JPA环境的配置

1.首先导入jar包放入lib目录下:

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

src下必须有一个META-INF文件夹,而且persistence.xml必须在其内,文件名必须相同
<?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=http://www.mamicode.com/"org.hibernate.dialect.MySQL5Dialect"/>> 

3.新建基本类用来测试:

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单元来测试:

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());
	}
}