十五、MyBatis进阶

一、日志

截屏2022-07-22 下午10.21.46.png
截屏2022-07-22 下午10.22.08.png
截屏2022-07-22 下午10.27.01.png

logback.xml



    
        
            %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
        
    

    
        
    

二、动态SQL

截屏2022-07-28 15.57.26.png
    
    @Test
    public void testDynamicSQL() throws Exception {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtils.openSession();
            HashMap param = new HashMap();
            param.put("categoryId",44);
            param.put("currentPrice",500);

            List list = sqlSession.selectList("goods.dynamicSQL",param);
            for (Goods goods : list) {
                System.out.println(goods);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            MybatisUtils.closeSession(sqlSession);
        }
    }

三、二级缓存

截屏2022-07-28 16.41.50.png
截屏2022-07-28 16.41.25.png
截屏2022-07-28 16.43.26.png
截屏2022-07-28 17.06.56.png

四、对象关联查询

1、一对多


    




    

        

        
    
    


    @Test
    public void testSelectOneToMany() throws Exception {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtils.openSession();
            List list = sqlSession.selectList("goods.selectOneToMany");
            for (Goods goods : list) {
                System.out.println(goods);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            MybatisUtils.closeSession(sqlSession);
        }
    }

2、多对一


    
        
        
        
    
    

    
    @Test
    public void testSelectMonyToOne() throws Exception {
        SqlSession sqlSession = null;

        try {
            sqlSession = MybatisUtils.openSession();
            List list = sqlSession.selectList("goodsDetail.selectManyToOne");

            for (GoodsDetail goodsDetail : list) {
                System.out.println(goodsDetail);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            MybatisUtils.closeSession(sqlSession);
        }
    }

五、分页插件PageHelper

截屏2022-07-29 15.35.48.png
截屏2022-07-29 15.37.07.png
        
            com.github.pagehelper
            pagehelper
            5.1.10
        

    
        

            

            
        
    
    

    @Test
    public void testSelectPage() throws Exception {
        SqlSession sqlSession = null;

        try {
            sqlSession = MybatisUtils.openSession();
            PageHelper.startPage(2,10);
            Page page = (Page)sqlSession.selectList("goods.selectPage");
            System.out.println("总页数:" + page.getPages());
            System.out.println("总记录数:" + page.getTotal());
            System.out.println("开始行号:" + page.getStartRow());
            System.out.println("结束行号:" + page.getEndRow());
            System.out.println("当前页码:" + page.getPageNum());

            List list = page.getResult();
            for (Goods goods : list) {
                System.out.println(goods);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            MybatisUtils.closeSession(sqlSession);
        }
    }

六、Mybatis整合C3P0连接池

        
            com.mchange
            c3p0
            0.9.5.4
        

C3P0DataSourceFactory.java类

package com.imooc.mybatis.datasource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;

//C3P0与MyBatis兼容使用的数据源工厂类
public class C3P0DataSourceFactory extends UnpooledDataSourceFactory {

    public C3P0DataSourceFactory() {
        this.dataSource = new ComboPooledDataSource();
    }
}




    
        
        
    

    
    
        
            
            
            
            
        
    

    
    
        
        
            
            
            
            
            

                

                

                
                
                
                
                
            
        
    

    
        
        
    


七、Mybatis整合Druid连接池

        
            com.alibaba
            druid
            1.1.14
        

DruidDataSourceFactory.java类

public class DruidDataSourceFactory extends UnpooledDataSourceFactory {
    public DruidDataSourceFactory() {
        this.dataSource = new DruidDataSource();
    }

    @Override
    public DataSource getDataSource() {
        try {
            ((DruidDataSource)this.dataSource).init();//初始化Druid数据源
        }catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return this.dataSource;
    }
}




    
        
        
    
    
        
        
            
            
            
            
            
            
                
                
                
                
                
            
        
    
    
        
    

八、Mybatis的批处理

批量插入

    
        insert into t_goods(title,sub_title,original_cost,current_price,discount,is_free_delivery,category_id)
        values
        
            (#{item.title},#{item.subTitle},#{item.originalCost},#{item.currentPrice},#{item.discount},#{item.isFreeDelivery},#{item.categoryId})
        
    
    @Test
    public void testBatchInsert() throws Exception {
        SqlSession sqlSession = null;

        try {
            long st = new Date().getTime();
            sqlSession = MybatisUtils.openSession();
            List list = new ArrayList();
            for (int i = 0; i <10000; i++) {
                Goods goods = new Goods();
                goods.setTitle("测试商品");
                goods.setSubTitle("测试子标题");
                goods.setOriginalCost(200f);
                goods.setCurrentPrice(100f);
                goods.setDiscount(0.5f);
                goods.setIsFreeDelivery(1);
                goods.setCategoryId(43);
                list.add(goods);
            }
            sqlSession.insert("goods.batchInsert", list);
            sqlSession.commit();
            long et = new Date().getTime();
            System.out.println("执行时间:" + (et -st) + "毫秒");
            
        } catch (Exception e) {
            throw e;
        } finally {
            MybatisUtils.closeSession(sqlSession);
        }
    }

批量删除

    
        delete from t_goods where goods_id in
        
            #{item}
        
    

    @Test
    public void testBatchDelete() {
        SqlSession session = null;
        try {
            long st = new Date().getTime();
            session = MybatisUtils.openSession();

            System.out.println("session" + session);

            List list = new ArrayList();
            list.add("1920");
            list.add("1921");
            list.add("1922");

            session.delete("goods.batchDelete",list);
            session.commit();
            long et = new Date().getTime();
            System.out.println(et - st);
        } catch (Exception e) {
            e.printStackTrace();
            if (session != null) {
                session.rollback();
            }
        } finally {
            MybatisUtils.closeSession(session);
        }
    }

九、Mybatis注解开发

截屏2022-07-30 下午3.15.59.png

mybatis-config.xml配置文件




    
        
    

    
        
            
            
                
                
                
                
            
        
    

    
        
        
    

GoodsDao.java接口

public interface GoodsDao {
    @Select("select * from t_goods where current_price between #{min} and #{max} order by current_price limit 0,#{limit}")
    public List selectByPriceRange(@Param("min") Float min, @Param("max") Float max, @Param("limit") Integer limit);

    @Insert("insert into t_goods(title,sub_title,original_cost,current_price,discount,is_free_delivery,category_id) values (#{title},#{subTitle},#{originalCost},#{currentPrice},#{discount},#{isFreeDelivery},#{categoryId})")
    @SelectKey(statement = "select last_insert_id()" ,before = false, keyProperty = "goodsId", resultType = Integer.class)
    public Integer insert(Goods goods);

    @Select("select * from t_goods")
    @Results({
            @Result(column = "goods_id", property = "goodsId", id = true),
            @Result(column = "title", property = "title"),
            @Result(column = "current_price", property = "currentPrice")
    })
    public List selectAll();
}

MybatisTestor.java测试类

public class MybatisTestor {
    @Test
    public void testSelectByPriceRange() throws Exception {
        SqlSession sqlSession = null;

        try {
            sqlSession = MybatisUtils.openSession();
            GoodsDao goodsDao = sqlSession.getMapper(GoodsDao.class);
            List list = goodsDao.selectByPriceRange(100F, 500F, 20);
            System.out.println(list.size());
        } catch (Exception e) {
            throw e;
        } finally {
            MybatisUtils.closeSession(sqlSession);
        }
    }

    @Test
    public void testInsert() {
        SqlSession session = null;
        try {
            session = MybatisUtils.openSession();

            Goods goods = new Goods();
            goods.setTitle("测试标题");
            goods.setSubTitle("测试副标题");
            goods.setOriginalCost(200f);
            goods.setCurrentPrice(100f);
            goods.setDiscount(0.5f);
            goods.setIsFreeDelivery(1);
            goods.setCategoryId(43);

            GoodsDao goodsDao = session.getMapper(GoodsDao.class);
            Integer num = goodsDao.insert(goods);
            session.commit();

            System.out.println(goods.getGoodsId());

        } catch (Exception e) {
            e.printStackTrace();
            if (session != null) {
                session.rollback();
            }
        } finally {
            MybatisUtils.closeSession(session);
        }
    }

    @Test
    public void testSelectAll() throws Exception {
        SqlSession sqlSession = null;

        try {
            sqlSession = MybatisUtils.openSession();
            GoodsDao goodsDao = sqlSession.getMapper(GoodsDao.class);
            List list = goodsDao.selectAll();
            System.out.println(list.size());
        } catch (Exception e) {
            throw e;
        } finally {
            MybatisUtils.closeSession(sqlSession);
        }
    }
}

你可能感兴趣的:(十五、MyBatis进阶)