使用JPA规范中的方法实现CRUD操作

使用JPA规范中的方法实现CRUD操作

第一步 导入jar

第二步 编写实体类并使用注解配置

第三步 创建配置文件

要求:在src下面的META-INF文件夹下面创建一个名称为persistence.xml的文件。

配置文件的内容:

"1.0" encoding="UTF-8"?>  

    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">    

      

    "myPersistUnit" transaction-type="RESOURCE_LOCAL">  

 

     

   org.hibernate.ejb.HibernatePersistence    

 

   

   com.domain.Customer

   

  

            

      

       

               hbm2ddl.auto" value="update" />  

                   

               

    value="com.mysql.jdbc.Driver" />    

               

value="jdbc:mysql://localhost:3306/hibernate_jpa"/>  

                   

                  

                  

               

    value="org.hibernate.dialect.MySQL5Dialect" />

                   

               

                   

                  

            

      

  

 

第四步 编写工具类

public final class JPAUtil {

//JPA的实体管理器工厂:相当于HibernateSessionFactory

private static EntityManagerFactory em;

//使用静态代码块赋值

static {

//注意:该方法参数必须和persistence.xmlpersistence-unit标签name属性取值一致

em = Persistence.createEntityManagerFactory("myPersistUnit");

}

 

/**

 * 使用管理器工厂生产一个管理器对象

 * @return

 */

public static EntityManager getEntityManager() {

return em.createEntityManager();

}

}

 

 JPACRUD操作

1.1.1 保存

/**

 * 保存一个实体

 */

@Test

public void testAdd(){  

//定义对象

Customer c = new Customer();

c.setCustName("XXXX");

c.setCustLevel("VIP客户");

c.setCustSource("网络");

c.setCustIndustry("IT教育");

c.setCustAddress("昌平区北七家镇");

c.setCustPhone("010-84389340");

EntityManager em=null;  

        EntityTransaction tx=null;  

        try{  

         //获取实体管理对象

         em=JPAUtil.getEntityManager();

         //获取事务对象

         tx=em.getTransaction();

         //开启事务

         tx.begin();

         //执行操作

         em.persist(c);

         //提交事务

         tx.commit();  

        }catch(Exception e){

         //回滚事务

         tx.rollback();

         e.printStackTrace();  

        }finally{  

         //释放资源

            em.close();  

        }    

    }

1.1.2 查询一个

/**

 * 查询一个:

 * 使用立即加载的策略

 */

@Test

public void testGetOne(){  

//定义对象

EntityManager em=null;  

         EntityTransaction tx=null;  

         try{  

         //获取实体管理对象

         em=JPAUtil.getEntityManager();

         //获取事务对象

         tx=em.getTransaction();

         //开启事务

         tx.begin();

         //执行操作

         Customer c1 = em.find(Customer.class, 1L);

         //提交事务

         tx.commit();  

         System.out.println(c1); //输出查询对象

         }catch(Exception e){

         //回滚事务

         tx.rollback();

         e.printStackTrace();  

         }finally{  

         //释放资源

             em.close();  

         }    

    }

 

1.1.3 修改

/**

 * 修改

 */

@Test

public void testUpdate(){  

//定义对象

EntityManager em=null;  

        EntityTransaction tx=null;  

        try{  

         //获取实体管理对象

         em=JPAUtil.getEntityManager();

         //获取事务对象

         tx=em.getTransaction();

         //开启事务

         tx.begin();

         //执行操作

         Customer c1 = em.find(Customer.class, 1L);

         c1.setCustName("XXXX");

         //提交事务

         tx.commit();  //使用JPA中快照机制实现更新

        }catch(Exception e){

         //回滚事务

         tx.rollback();

         e.printStackTrace();  

        }finally{  

         //释放资源

            em.close();  

        }    

    }

 

1.1.4 删除

/**

 * 删除

 */

@Test

public void testRemove(){  

//定义对象

EntityManager em=null;  

         EntityTransaction tx=null;  

         try{  

         //获取实体管理对象

         em=JPAUtil.getEntityManager();

         //获取事务对象

         tx=em.getTransaction();

         //开启事务

         tx.begin();

         //执行操作

         Customer c1 = em.find(Customer.class, 6L);

         em.remove(c1);

         //提交事务

         tx.commit();

         }catch(Exception e){

         //回滚事务

         tx.rollback();

         e.printStackTrace();  

         }finally{  

         //释放资源

             em.close();  

         }    

    }

查询实体的缓存问题

@Test

public void testGetOne(){  

//定义对象

EntityManager em=null;  

        EntityTransaction tx=null;  

        try{  

         //获取实体管理对象

         em=JPAUtil.getEntityManager();

         //获取事务对象

         tx=em.getTransaction();

         //开启事务

         tx.begin();

         //执行操作

         Customer c1 = em.find(Customer.class, 1L);

         Customer c2 = em.find(Customer.class, 1L);

         System.out.println(c1 == c2);//输出结果是trueEntityManager也有缓存

         //提交事务

         tx.commit();  

         System.out.println(c1);

        }catch(Exception e){

         //回滚事务

         tx.rollback();

         e.printStackTrace();  

        }finally{  

         //释放资源

            em.close();  

        }    

    }

 

延迟加载策略的方法:

/**

 * 查询一个:

 * 使用延迟加载策略

 */

@Test

public void testLoadOne(){  

//定义对象

EntityManager em=null;  

        EntityTransaction tx=null;  

        try{  

         //获取实体管理对象

         em=JPAUtil.getEntityManager();

         //获取事务对象

         tx=em.getTransaction();

         //开启事务

         tx.begin();

         //执行操作 延迟加载

         Customer c1 = em.getReference(Customer.class, 1L);

         //提交事务

         tx.commit();  

         System.out.println(c1);

        }catch(Exception e){

         //回滚事务

         tx.rollback();

         e.printStackTrace();  

        }finally{  

         //释放资源

            em.close();  

        }    

    }

1.1.5 查询所有

/**

 * 查询所有

 * 涉及的对象:

 * Query(注意:不是Hibernate的Query)

 *   如何获取:

 *   使用EntityManagercreateQuery(String JPQL)方法;

 *   参数的含义

 *   JPQL:jpa  query language

 *   JPQL的写法:

 *   表名使用实体类名称替代

 *   列名使用实体类属性名称替代

 *   不能使用*号。查询所有,需要在from关键字后面的类名上加别名

 *   例如: select c from Customer c

 *   查询条件可以使用?作为参数占位符。

 *   给占位符赋值时,占位符索引位置从1开始

 * 获取结果集的方法

 * getResultList():查询结果是一个List集合

 * getSingleResult():查询结果是一个对象

 */

@Test

public void testFindAll(){

//定义对象

EntityManager em=null;  

        EntityTransaction tx=null;  

        try{  

         //获取实体管理对象

         em=JPAUtil.getEntityManager();

         //获取事务对象

         tx=em.getTransaction();

         //开启事务

         tx.begin();

         //执行操作

         Query query = em.createQuery("select c from Customer c where custName like ? ");

         query.setParameter(1,"%XX%");

         List list = query.getResultList();

         //提交事务

         tx.commit();

        

         for(Object o : list){

         System.out.println(o);

         }

        }catch(Exception e){

         //回滚事务

         tx.rollback();

         e.printStackTrace();  

        }finally{  

         //释放资源

            em.close();  

        }   

}

你可能感兴趣的:(框架)