【Spring Date JPA】二、JPA基本使用

抽取工具类 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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_popo_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值