Java小白学习指南【day48】---你不知道的Mybatis进阶

一、Mybatis使用回顾

mybatis回顾
1.导包(核心包,依赖包,测试)
2.核心配置文件
3.实体&表
4.mapper和对应的xml
5.MyBatisUtil 获取数据库连接对象
6.测试

使用Idea创建Maven项目,步骤:

1、准备数据库,创建项目

准备好需要的数据库,同时在Idea中创建普通的Maven项目

1606357865121
最终结构

1606357921395

2、Maven进行导包

以前是需要手动进行导包,现在只需要在pom.xml进行写入,maven会在本地仓库与中央仓库进行配置

<dependencies>
        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.1</version>
        </dependency>
        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>
        <!-- junit测试包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <!--作用域,删了以后可以在所有包内进行测试@test-->
            <scope>test</scope>
        </dependency>
    </dependencies>

3、添加核心配置文件 mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 加载jdbc.properties-->
    <properties resource="jdbc.properties"/>
    <!--申明操作数据库的环境-->
    <environments default="MYSQL">
        <environment id="MYSQL">
            <!--使用jdbc的事务-->
            <transactionManager type="JDBC"/>
            <!--支持连接池-->
            <dataSource type="POOLED">
                <!--自动补全结构:ctrl+shift+回车-->
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="driver" value="${jdbc.driverClassName}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 加载mapper.xml文件-->
        <mapper resource="cn/itsource/mybatisPractice/mapper/ProductMapper.xml"/>
    </mappers>
</configuration>

4、根据数据库数据创建模型(domain)

根据数据库中的字段按照标准的JavaBean创建即可

public class Product {
    
    
    private Long id;
    private String name;
    private BigDecimal price;
    ......
}

5、数据层的基本配置

创建对应的productMapper接口------>创建mapper的映射xml------->在mybatis-config.xml加载mapper.xml文件

6、创建MyBatisUtils

public class MybatisUtils {
    
    
    //单例模式创建一个SqlSessionFactory
    public static SqlSessionFactory sessionFactory;
    static {
    
    
        try {
    
    
            //获取到输入流
            InputStream resource = Resources.getResourceAsStream("mybatis-config.xml");
            //根据输入流创建工厂对象
            sessionFactory = new SqlSessionFactoryBuilder().build(resource);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
    //返回对应的对象
    public static SqlSession openSession(){
    
    
        if (sessionFactory != null){
    
    
            return sessionFactory.openSession();
        }
            return null;
    }
}

7、功能测试

public class TestMybatisPractice {
    
    
    @Test
    public void testFindAll(){
    
    
        //获取会话对象
        SqlSession session = MybatisUtils.openSession();
        //拿到映射对象,进行响应的操作
        ProductMapper mapper = session.getMapper(ProductMapper.class);
        mapper.findAll().forEach(System.out::println);
    }
}

二、Mybatis动态sql

1、批量插入数据

ProductMapper.xml

  <!--public void saveMany(List<Product> list);-->
    <insert id="saveMany" >
        INSERT INTO product (name,price) VALUES
        <!--
		collection="list":接收传过来的集合
        item="p":每次遍历接收的一个对象
        separator=",": 动态分隔符  我们使用,分割-->
        <foreach collection="list" item="l" separator=",">
            (#{l.name},#{l.price})
        </foreach>
    </insert>

注意:

​ mybatis : mapper接口传过来的集合或者数组,它会自动帮我们封装成Map<key,value>
​ 它直接帮我们定义好固定的key的值就是:
​ 如果接口中传的是集合,那么key的值是:list
​ 如果接口中传的是数组,那么key的值是:array

​ value就是我们的集合或者数组本身(值)

测试

@Test
    public void testSaveMany(){
    
    
        //获取会话对象
        SqlSession session = MybatisUtils.openSession();
        //拿到映射对象,进行响应的操作
        ProductMapper mapper = session.getMapper(ProductMapper.class);
        List<Product> Products = Arrays.asList(
                new Product("小黄瓜",new BigDecimal(69)),
                new Product("西红柿",new BigDecimal(78))
        );
        //执行功能
        mapper.saveMany(Products);
        //提交事务
        session.commit();
    }

注意:一定要执行提交事务

2、批量删除

ProductMapper.xml

    <!--public void deleteById(List<Long> ids);-->
    <delete id="deleteById" >
        DELETE FROM product WHERE id IN
        <foreach collection="list" item="ids" separator="," open="(" close=")">
            #{ids}
        </foreach>
    </delete>

进行测试

 @Test
    public void testDeleteById(){
    
    
        //获取会话对象
        SqlSession session = MybatisUtils.openSession();
        //拿到映射对象,进行响应的操作
        ProductMapper mapper = session.getMapper(ProductMapper.class);
        List<Long> ids = Arrays.asList(9L,10L);
        //执行功能
        mapper.deleteById(ids);
        //提交事务
        session.commit();
    }

3、foreach中的属性

(1)collection=“list” 使用集合的话,默认就是使用list与collection来接收
(2)separator="," 每遍历一次后的分隔符
(3)item=“p” 每次遍历的这个对象别名,可以修改
(4)index:获取当前遍历索引(一般没有作用)
(5)open:拼接sql以什么开始
);
//提交事务
session.commit();
}

猜你喜欢

转载自blog.csdn.net/WLK0423/article/details/114223252