JPA实现的CRUD

          SUN引入新的JPA ORM规范出于两个原因:其一,简化现有javaEE和javaSE应用开发,其二:SUN希望整合ORM技术,实现天下归一。
          JPA由EJB3.0软件专家组开发,作为JSR-220实现的一部分。但不不基于EJB3.0,你可以在web应用中,甚至桌面应用中使用。JPA的宗旨
是为POJO提供持久化标准规范,由此可见,经过这几年的实践探索,能够脱离容器独立运行,方便开发和测试的理念已经深入人心了。
Hibernate,Toplink以及OpenJPA都提供了JPA的实现。
        在JPA中需要一个配置文件来描述持久化单元,该配置文件定义在一个称为persistence.xml的XML文件中,每个持久化单元均被命名,所以当一个引用应用程序想要为实体指定配置时,它只需要医用这个定义了配置的持久化单元的名称。单个persistence.xml文件可以包含一个或者多个已经命名的持久化单元配置,但是每个持久化单元是独立于其他的持久化单元的。
        例如,persistence.xml文件中的元素:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="JPA-API1" transaction-type="RESOURCE_LOCAL"> 
 <provider>org.hibernate.ejb.HibernatePersistence</provider>
 <!-- 添加持久化类 -->
 <class>com.silence.entities.Employee</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 实现产品的基本属性. 配置 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>
                persistence-unit元素的那么特性表示持久化单元的名称,它是创建EntityManagerFactory字符串时指定的字符串。我们必须使"JPA-API1"用该字符串作为名称,transaction-type="RESOURCE_LOCAL"表明持久化单元使用资源的级别的EntityTransaction(事实事务),而不是JTA事务。class元素列出持久还单元一部分的实体,当存在多个实体时,可以指定多个class属性,当然,我们在开发javaEE时是不需要我们手动指定的,因为javaEE的容器会自动扫描它们,但是在javaSE上运行时,需要指定它们便于便携式的执行。
com.silence.entities包中的持久化类:
package com.silence.entities;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
private int id;
private String name;
private long salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
public Employee(int id, String name, long salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
public Employee() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
}
}

         这个类只包含了三个属性,为了把Employee转化为一个实体,首先需要以@Entity注解该类。它仅仅是一个标记注解,用于通知持久化引擎类是一个实体。@Id它注解了特定字段用于保存实体持久化标识的主键。关于多数的注解和用法在这里不一一展开。

EmployeeService类:


package com.silence.test;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import com.silence.entities.Employee;

public class EmployeeService {
protected EntityManager em;
public EmployeeService(EntityManager em) {
this.em = em;
}
public Employee createEmployee(int id, String name, long salary) {
Employee emp = new Employee();
emp.setName(name);
emp.setSalary(salary);
em.persist(emp);
return emp;
}
public void removeEmployee(int id) {
Employee emp = findEmployee(id);
if (emp != null) {
em.remove(emp);
}
}
public Employee raiseEmployeeSalary(int id, long raise) {
Employee emp = em.find(Employee.class, id);
if (emp != null) {
emp.setSalary(emp.getSalary() + raise);
}
return emp;
}
public Employee findEmployee(int id) {
return em.find(Employee.class, id);
}

public List<Employee> findAllEmployees() {
TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e", Employee.class);
return query.getResultList();
}
}

其中em是一个实体管理器,它来自EntityManagerFactory类型的工厂,就像hibernate中的Session和SessionFactory

的关系。

package com.silence.test;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.silence.entities.Employee;

public class test {

private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
private EmployeeService service = null;

@Before
public void getEntityManagerFactory(){
    entityManagerFactory = Persistence.createEntityManagerFactory("JPA-API1");
    entityManager = entityManagerFactory.createEntityManager();
    service = new EmployeeService(entityManager);
    entityManager.getTransaction().begin();
}
@After
public void closeManager(){
  entityManager.getTransaction().commit();
  entityManager.close();
  entityManagerFactory.close();
}

        //查找所有Employee操作
@Test
public void findAll(){
List<Employee> list = service.findAllEmployees();
for(Employee e:list){
System.out.println(e);
}
}

        //查找Employee操作
@Test
public void find(){
Employee emp = service.findEmployee(1);
System.out.println(emp);
}

       //添加Employee操作
@Test
public void testAdd(){
Employee em = service.createEmployee(4, "silence1", 10000001);
System.out.println("persistence");
}
}

test方法

package com.silence.test;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.silence.entities.Employee;


public class test {

private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
private EmployeeService service = null;

@Before
public void getEntityManagerFactory(){
    entityManagerFactory = Persistence.createEntityManagerFactory("JPA-API1");
    entityManager = entityManagerFactory.createEntityManager();
    service = new EmployeeService(entityManager);
    entityManager.getTransaction().begin();
}
public static void main(String[] args) {

}
@After
public void closeManager(){
  entityManager.getTransaction().commit();
  entityManager.close();
  entityManagerFactory.close();
}

@Test
public void deleteEmployee(){
Employee emp = service.removeEmployee(1);
System.out.println(emp);
}

@Test
public void upateEmployee(){
   Employee emp = service.raiseEmployeeSalary(1, 120);
System.out.println(emp);
}
@Test
public void findAll(){
List<Employee> list = service.findAllEmployees();
for(Employee e:list){
System.out.println(e);
}
}
@Test
public void find(){
Employee emp = service.findEmployee(1);
System.out.println(emp);
}
@Test
public void testAdd(){
Employee em = service.createEmployee(4, "silence1", 10000001);
System.out.println("persistence");
}
}

       因为程序作为一个简单的javaSE应用程序运行,需要把相应的jar文件加入到classpath下,同时,需要加入mysql数据库驱动,JPA实现茶品hibernate的相应的jar包。

你可能感兴趣的:(JPA实现的CRUD)