persistence.xml文件内容
<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">
<persistence-unit name="jap_1" transaction-type="RESOURCE_LOCAL">
<!-- 配置使用什么ORM产品来作为JPA的实现
1.实际上配置的是 Javax.persistence.spi.Persistenceprovider接口的实现类
2.若JPA项目中只有一个JPA的实现产品,则也可以不配置该节点 -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<!-- 添加持久化类 -->
<class>com.jpa.Customer</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa" />
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
JpaTest
测试父类文件内容
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
public class JpaTest {
EntityManagerFactory entityManagerFactory;
EntityManager entityManager;
EntityTransaction transaction;
@Before
public void init() {
// 1.创建 Entitymanager Factory
String persistenceUnitName = "jap_1";
entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
// 2.创建 EntityManager
entityManager = entityManagerFactory.createEntityManager();
// 3.开启事务
transaction = entityManager.getTransaction();
transaction.begin();
}
@After
public void destroy() {
transaction.commit();
entityManager.close();
entityManagerFactory.close();
}
}
Test1
子类具体实现
import org.junit.Test;
import com.jpa.Customer;
public class Test1 extends JpaTest {
@Test
public void test1() {
Customer customer = entityManager.find(Customer.class, 4);
System.out.println(customer.toString()); }
}