使用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="japDemo" transaction-type="RESOURCE_LOCAL">
<!-- 配置使用产品实现jpa -->
<!-- 实际上是配置实现javax.persistence.spi.PersistenceProvider接口的实现类 -->
<!-- 若项目中只有一个实现该接口的类,该节点也可不配置 -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.pan.entity.User</class>
<properties>
<!-- 配置数据库 -->
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa"/>
<!-- 配置hibernate属性 -->
<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>
transaction-type:指定JPA 的事务处理策略。RESOURCE_LOCAL:默认值,数据库级别的事务,只能针对一种数据库,不支持分布式事务。如果需要支持分布式事务,使用JTA:transaction-type="JTA“。
新建一个实体类
package com.pan.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="t_user")
public class User {
@Id
@Column(name="ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column(name="NAME",length=50)
private String name;
@Column(name="EMAIL",length=50)
private String email;
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;
}
}
测试代码:
@Test
public void helloWorld(){
//1.创建EntityManagerFactory
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("japDemo");
//2.创建EntityManager
EntityManager entityManager = entityManagerFactory.createEntityManager();
//3.开启事务
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
//4.持久化操作
User user = new User();
user.setName("pan");
user.setEmail("pan@126.com");
entityManager.persist(user);
//5.提交事务
transaction.commit();
//6.关闭EntityManager
entityManager.close();
//7.关闭EntityManagerFactory
entityManagerFactory.close();
}
这样简单的helloworld就完成了。