JavaSE中Jpa的應用入門
一. JPa提供的用戶接口
Persistence,EntityMangerFactory,EntityManager
二. 配置.
1.添加Jar包
以hibernate作爲Jpa的實現進行.
添加hibernate的jar包.
添加hibernate-entitymanager的jar包
2.配置persistence.xml文件
在src下新建文件夾META-INF
在MET-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_1_0.xsd" version="1.0">
<persistence-unit name="Emp" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>org.jenfer.jpa.entity.Emp</class>
<properties>
<property name = "hibernate.connection.driver_class" value = "com.mysql.jdbc.Driver"/>
<property name = "hibernate.connection.url" value = "jdbc:mysql://localhost/test"/>
<property name = "hibernate.connection.username" value = "root"/>
<property name = "hibernate.connection.password" value = "fox"/>
<property name = "hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
說明: persistence-unit是持久化單元的名字
< provider/>:JPA實現提供程序
<class/>持久化的類
<properties/> 實現廠商自定義的屬性
這裏是hibernate的自定屬性.相關資料參考hibernate的配置
三. 實體類的實現:
以下是是用Jpa的註解的POJO.
@Table,@Entity等請參考Jpa官方文檔
@Table(name = "emp")
@Entity(name = "Emp")
public class Emp {
@Id
@Column(name = "emp_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int empId;
@Column(name = "emp_name", length = 10)
private String empName;
private String email;
/**
* Default constructor
*/
public Emp() {
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
四. 測試類庫的編寫.用到Junit測試框架
public class EvnTest {
private static EntityManager manager;
@BeforeClass
public static void init() {
EntityManagerFactory factory = Persistence
.createEntityManagerFactory("Emp");
manager = factory.createEntityManager();
}
@AfterClass
public static void destory(){
if(manager!=null){
manager.close();
}
}
@Test
@Ignore
public void envTest() {
Emp emp = new Emp();
emp.setEmail("[email protected]");
emp.setEmpName("周星馳");
EntityTransaction tx = manager.getTransaction();
try {
tx.begin();
manager.persist(emp);
tx.commit();
} catch (Exception e) {
tx.rollback();
}
}
@Test@Ignore
public void queryTest() {
Emp emp=manager.find(Emp.class, 1);
System.out.println(emp.getEmpName());
}
@Test@Ignore
public void updateTest(){
Emp emp = new Emp();
emp.setEmail("[email protected]");
emp.setEmpName("周劍華");
emp.setEmpId(1);
EntityTransaction tx = manager.getTransaction();
try {
tx.begin();
manager.<Emp>merge(emp);
tx.commit();
}