抽取工具类 JpaUtils
/**
* 解决实体管理器工厂的浪费资源和耗时问题
* 通过静态代码块的形式,当程序第一次访问此工具类时,创建一个公共的实体管理器工厂对象
*
* 当程序第一次访问 getEntityManager 方法,会先经过静态代码块创建一个 factory,再执行到方法创建 管理器
* 第二次访问时,直接通过一个已经创建好的factory,创建实体管理器
*/
public class JpaUtils {
private static EntityManagerFactory entityManagerFactory;
/**
* 公共实体管理器工厂
*/
static {
//1.加载配置文件,创建entityManagerFactory
entityManagerFactory = Persistence.createEntityManagerFactory("myJpa");
}
/**
* 获取 entityManager
*/
public static EntityManager getEntityManager(){
return entityManagerFactory.createEntityManager();
}
}
延迟加载与立即加载
public class JpaTest {
/**
* 测试根据id查询
* 使用 find 方法查询
* 1.查询的对象就是当前客户对象本身
* 2.在调用 find 方法的时候,就会发送sql语句查询数据库
*
* 立即加载
*/
@Test
public void testFindById(){
EntityManager entityManager = JpaUtils.getEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
Customer customer = entityManager.find(Customer.class, 1l);
System.out.println(customer);
transaction.commit();
entityManager.close();
}
/**
* 测试根据id查询
* 使用 getReference 方法查询
* 1.获取的对象是一个动态代理对象
* 2.在调用 getReference 方法的时候,不会立即发送sql语句查询数据库
* * 而是当调用查询结果对象的时候,才会发送查询的 sql 语句
* * 什么时候用,什么时候发送查询sql语句
*
* 延迟加载(懒加载)
* * 得到的是一个动态代理对象
* * 什么时候用,什么时候查询
*
*/
@Test
public void testReferrence(){
EntityManager entityManager = JpaUtils.getEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
Customer customer = entityManager.getReference(Customer.class, 1l);
System.out.println(customer);//调用customer时
transaction.commit();
entityManager.close();
}
}
删除与更新
先查询,再删除
Customer customer = entityManager.getReference(Customer.class, 1l);
entityManager.remove(customer);
先查询,再更新
Customer customer = entityManager.getReference(Customer.class, 2l);
customer.setCustIndustry("IT教育");
entityManager.merge(customer);