一:首先导入JPA依赖的jar文件
二:JPA的配置文件
JPA规范要求在类路径的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">
<!-- 配置持久化单元 ,可以配置多个,但是名称不能重复
name:用于指定持久化单元名称
transaction-type:指定事务类型
-->
<persistence-unit name="myJPAUnit" transaction-type="RESOURCE_LOCAL">
<!-- 注意在5.3.1版本中,provider为org.hibernate.jpa.HibernatePersistenceProvider
而不是org.hibernate.ejb.HibernatePersistence
-->
<!--<provider>org.hibernate.ejb.HibernatePersistence</provider>-->
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<!-- 指定JPA注解的实体类位置 -->
<class>entity.Customer</class>
<!-- 连接数据库的配置,其实就是hibernate.cfg.xml的内容 -->
<properties>
<!-- 第一部分:连接数据库的信息 -->
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"></property>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/hibernate?characterEncoding=UTF-8 "></property>
<property name="hibernate.connection.username" value="root"></property>
<property name="hibernate.connection.password" value="123456"></property>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"></property>
<!-- 可选配置 -->
<!-- 显示sql语句 -->
<property name="hibernate.show_sql" value="true"></property>
<!-- 格式化输出sql语句 -->
<property name="hibernate.format_sql" value="true"></property>
<!-- 采用哪种方式生成DDL语句
update:表示检查实体类的映射配置和数据库的表结构是否一致,如果不一致,更新表结构
-->
<property name="hibernate.hbm2ddl.auto" value="update"></property>
</properties>
</persistence-unit>
</persistence>
三 ,
@Test
public void test01(){
Customer customer = new Customer();
customer.setCustName("JPA");
//获取EntityManager对象
EntityManager em = JPAUtil.createEntityManager();
//开启EntityTransaction事务
EntityTransaction etx = em.getTransaction();
etx.begin();
//保存操作
em.persist(customer);
/*
* 增加:
* em.persist(customer);
* 查找:
* em.find(Customer.class, 1);
* 更新:
* em.merge(customer);
* 删除
* em.remove(customer);
*
*/
//提交事务
etx.commit();
em.close();
}
@Test
public void test02(){
Customer customer = new Customer();
customer.setCustName("JPA");
//获取EntityManager对象
EntityManager em = JPAUtil.createEntityManager();
//开启EntityTransaction事务
EntityTransaction etx = em.getTransaction();
etx.begin();
Query query = em.createQuery("select c from Customer c");
List<Customer> list = query.getResultList();
for(Customer os:list){
System.out.println(os);
}
//提交事务
etx.commit();
em.close();
}