Java Novice Learning Guide [day48]---Advanced Mybatis that you don’t know

One, Mybatis use review

Mybatis review
1. Guide package (core package, dependent package, test)
2. Core configuration file
3. Entity & table
4. Mapper and corresponding xml
5. MyBatisUtil to obtain database connection object
6. Test

Use Idea to create a Maven project, steps:

1. Prepare the database and create the project

Prepare the required database and create a normal Maven project in Idea

1606357865121
Final structure

1606357921395

2. Maven guides the package

In the past, it was necessary to manually guide the package, but now it only needs to be written in pom.xml, and maven will configure it in the local warehouse and the central warehouse.

<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. Add the core configuration file 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. Create a model (domain) based on database data

Create according to the standard JavaBean according to the fields in the database

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

5. The basic configuration of the data layer

Create the corresponding productMapper interface------>Create mapper mapping xml------->Load the mapper.xml file in mybatis-config.xml

6. Create 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. Functional test

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

Two, Mybatis dynamic sql

1. Insert data in batches

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>

note:

​ mybatis: The collection or array passed by the mapper interface, it will automatically help us encapsulate it into Map<key,value>
​ It directly helps us define the fixed key value is:
​ If the interface passes a collection, then the key The value is: list
​ If the interface is passed an array, then the value of key is: array

​ value is our collection or array itself (value)

test

@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();
    }

Note: must perform the commit transaction

2. Batch delete

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>

carry out testing

 @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. Attributes in foreach

(1) collection="list" If you use a collection, the default is to use list and collection to receive
(2) separator="," the separator after each traversal
(3) item="p" This object alias for each traversal , You can modify
(4) index: get the current traversal index (generally no effect)
(5) open: where does the splicing SQL start
);
//Submit the transaction
session.commit();
}

Guess you like

Origin blog.csdn.net/WLK0423/article/details/114223252