1.jpa的环境配置
a.导入jpa所用的jar包,根据jpa的实现框架不同,其jar包也不同
b.新建如下配置文件src/META-INF/persistence.xml的配置文件
src下必须有一个META-INF文件夹,而且persistence.xml必须在其内,文件名必须相同。
<?xml version="1.0"?> <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_1_0.xsd" version="1.0"> <persistence-unit name="zsm" transaction-type="RESOURCE_LOCAL"> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> <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/eshop?useUnicode=true&characterEncoding=UTF-8"/> <property name="hibernate.max_fetch_depth" value="3"/> <property name="hibernate.hbm2ddl.auto" value="update"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="false"/> </properties> </persistence-unit> </persistence>
c.测试jpa环境(jpa的入口是Persistence类):
package com.bean.product; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class ProductType { private int id; @Id @GeneratedValue(strategy = GenerationType.AUTO) public int getId() { return id; } public void setId(int id) { this.id = id; } }
package com.test; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.junit.BeforeClass; import org.junit.Test; import com.bean.product.ProductType; public class ProdutctTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void test() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("zsm"); EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); em.persist(new ProductType()); em.getTransaction().commit(); em.close(); factory.close(); } }