Spring JPA基本使用(增删改查)

Spring JPA基本使用(增删改查)

  1. 封装工具类

    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    
    public class JpaUtils {
        private static EntityManagerFactory factory;
    
        static {
            factory = Persistence.createEntityManagerFactory("myJpa");
        }
    
        //获取实体管理器对象
        public static EntityManager getEntityManager(){
            return factory.createEntityManager();
        }
    }
    
  2. 根据id(主键)查询:l两种方式find和getReference

    两种方式的区别

    /*
        * 根据id查询
        * 使用find方式查询(立即加载)
        *   1.查询的对象就是当前客户对象本身
        *   2.在调用find方法的时候,就会发送sql语句查询数据库
        * 使用getReference方式查询(延迟加载)
        *   1.获取到的对象是一个动态代理对象
        *   2.调用getReference不会立即发送sql语句查询数据,
        *       当调用查询结果对象的时候,才会发送查询的sql语句,什么时候用,什么时候查询
        * */
    

    find方式

    /*
        * 根据id查询
        * */
    @Test
    public void testFind(){
        EntityManager em = JpaUtils.getEntityManager();
        //获取事务对象
        EntityTransaction tx = em.getTransaction();
        //开启事务
        tx.begin();
        //参数1:查询结果实体类的字节码  参数2:查询的主键的取值
        Customer customer = em.find(Customer.class, 1);
        System.out.println(customer);
        tx.commit();
        em.close();
    }
    

    getReference方式

    @Test
    public void testReference(){
        EntityManager em = JpaUtils.getEntityManager();
        //获取事务对象
        EntityTransaction tx = em.getTransaction();
        //开启事务
        tx.begin();
        //参数1:查询结果实体类的字节码  参数2:查询的主键的取值
        Customer customer = em.getReference(Customer.class, 1);
        System.out.println(customer);
        tx.commit();
        em.close();
    }
    
  3. 删除操作

    //删除操作
    @Test
    public void testRemove(){
        EntityManager em = JpaUtils.getEntityManager();
        //获取事务对象
        EntityTransaction tx = em.getTransaction();
        //开启事务
        tx.begin();
        //先根据id查询出客户
        Customer customer = em.getReference(Customer.class, 1);
        //删除客户 删除什么数据就把实体类对象作为参数
        em.remove(customer);
        tx.commit();
        em.close();
    }
    
  4. 修改操作

    //修改操作
    @Test
    public void testmMerge(){
        EntityManager em = JpaUtils.getEntityManager();
        //获取事务对象
        EntityTransaction tx = em.getTransaction();
        //开启事务
        tx.begin();
        //先根据id查询出客户
        Customer customer = em.getReference(Customer.class, 1);
        //修改
        customer.setIndustry("教育");
        em.merge(customer);
        tx.commit();
        em.close();
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值