JPA persistence.xml 测试类相关写法

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());	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值