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

使用 JPA 规范中的方法实现 CRUD 操作
第一步 导入jar
第二步 编写实体类并使用注解配置
第三步 创建配置文件
要求: src 下面的 META-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_2_0.xsd"  
    version="2.0">     
    <!--Name 属性用于定义持久化单元的名字 (name 必选 , 空值也合法 );   
      transaction-type 指定事务类型 ( 可选 )    
      取值:
      JTA :默认值
      RESOURCE_LOCAL
-->  
     < persistence-unit   name = "myPersistUnit"   transaction-type = "RESOURCE_LOCAL" >   
 
   <!-- javax.persistence.PersistenceProvider 接口的一个实现类 ( 可选 ) -->  
    < provider > org.hibernate.ejb.HibernatePersistence </ provider >     
 
   <!-- 显式列出实体类 , Java SE 环境中应该显式列出 .( 可选 ) -->
   < class >com.domain.Customer</ class >
   
  
   <!-- 厂商专有属性 ( 可选 ) 我们用的 Hibernate ,后面都是 hibernate.cfg.xml 中配置 -->         
   < properties >     
        <!-- 生成 DDL 的策略 -->
                < property   name ="hibernate. hbm2ddl .auto" value ="update" />   
                <!-- 数据库的连接信息 -->     
                < property   name ="hibernate.connection.driver_class"
     value ="com.mysql.jdbc.Driver" />     
                < property   name ="hibernate.connection.url"
value ="jdbc:mysql://localhost:3306/hibernate_jpa" />   
                < property   name ="hibernate.connection.username" value ="root" />     
                < property   name ="hibernate.connection.password" value =" root " />    
                <!-- 指定方言 -->    
                < property   name ="hibernate.dialect"
     value ="org.hibernate.dialect.MySQL5Dialect" />
                <!-- 是否显示 SQL 语句 -->     
                < property   name ="hibernate.show_sql" value ="false" />
                <!-- 是否格式化 SQL 语句 -->     
                < property   name ="hibernate.format_sql" value ="true" />    
         </ properties >     
     </ persistence-unit >   
</ persistence >   

第四步 编写工具类
public   final   class  JPAUtil {
//JPA 的实体管理器工厂:相当于 Hibernate SessionFactory
private   static  EntityManagerFactory em ;
// 使用静态代码块赋值
static  {
// 注意:该方法参数必须和 persistence.xml persistence-unit 标签 name 属性取值一致
em  = Persistence. createEntityManagerFactory ( "myPersistUnit" );
}
 
/**
 * 使用管理器工厂生产一个管理器对象
 * @return
 */
public   static  EntityManager getEntityManager() {
return   em .createEntityManager();
}
}

 JPA CRUD 操作
1.1.1  保存
/**
 * 保存一个实体
 */
@Test
public   void  testAdd(){  
// 定义对象
Customer c = new  Customer();
c.setCustName( " XX学院 " );
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(" XX学院 ");
         // 提交事务
         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);// 输出结果是 true EntityManager 也有缓存
         // 提交事务
         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)
 *   如何获取:
 *   使用 EntityManager createQuery(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,"% 学院 %");
         List  list = query.getResultList();
         // 提交事务
         tx.commit();
        
         for (Object o : list){
         System. out .println(o);
         }
        } catch (Exception e){
         // 回滚事务
         tx.rollback();
         e.printStackTrace();  
        } finally {  
         // 释放资源
            em.close();  
        }   
}

猜你喜欢

转载自blog.csdn.net/yahweh_liu/article/details/80682434