一、JPA的helloword实例。
使用Eclipse创建JPA工程,会自动生成persistence.xml文件。
文件的配置如下 :
<?xml version="1.0" encoding="UTF-8"?>
<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="JPA_1" transaction-type="RESOURCE_LOCAL">
<!-- 配置使用什么 ORM产品作为JPA的实现 -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<!-- 添加持久化类 -->
<class>com.jpa.helloword.Customer</class>
<!-- 连接数据库配置 -->
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<!-- 配置JPA实现产品的配置 -->
<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>
持久化实体类:
/**
*
*/
package com.jpa.helloword;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author 徐庶
* @date 2016年12月10日
*/
@Table(name="JPA_CUSTOMERS")
@Entity
public class Customer {
private Integer id;
private String name;
private String email;
private int age;
@GeneratedValue(strategy=GenerationType.AUTO)
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
测试类如下:
/**
*
*/
package com.jpa.helloword;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.junit.Test;
/**
* @author 徐庶
* @date 2016年12月10日
*/
public class Main {
@Test
public void jpa() {
//1.创建EntityManagerFactory
String persistenceUnitName="JPA_1";//该名称就是persistence-unit的name
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
//2.创建EntityManager
EntityManager entityManager = entityManagerFactory.createEntityManager();
//3.开启事务
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
//4.持久化操作
Customer customer=new Customer();
customer.setName("tom");
customer.setAge(12);
customer.setEmail("tom@163.com");
entityManager.persist(customer); //保存
//5.提交事务
transaction.commit();
//6.关闭 entityManager
entityManager.close();
//7.关闭 entityManagerFactory
entityManagerFactory.close();
}
}
该Demo所需要的jar包。
JPA的Helloword测试Demo至此完成,该程序运行成功后数据库中会插入一条数据。