MyBatis use-2-MyBatis label use

table of Contents

0, Maven project structure

1. The global configuration file of MyBatis: myBatis-config.xml

1.1 properties: Import external configuration files

1.1.1 Database configuration file: jdbc.properties

1.1.2 MyBatis global configuration file: myBatis-config.xml

1.2 settings: Set the properties of MyBatis

1.2.1 mapUnderscoreToCamelCase: Turn on automatic matching of camel case naming

1.3 typeAlisses: the alias of the class defined in the project

1.4 typeHandlers: database type and java type mapping

1.5 plugins: MyBatis plugin

1.6 environments: MyBatis configures multiple environments

1.7 databaseIdProvider: MyBatis supports a variety of different database vendors

1.7.1 Different types of database vendor configuration: jdbc.properties

1.7.2 MyBatis global configuration file gives aliases to different database vendors: mybatis-config.xml

1.7.3 Environment configuration under different database environments in MyBatis global configuration file: mybatis-config.xml

1.7.4 Use different database vendor IDs in the mapper.xml file

1.7.5 The xxxMapper.xml configuration file corresponding to each table needs to be registered in the MyBatis global configuration file to be used

2. MyBatis mapping file

2.1 Adding, deleting, modifying and checking MyBatis

2.1.1 EmployeeTest class

2.1.2 EmployeeDao interface

2.1.3 EmployeeMapper.xml

2.1.4 Test results

2.2 When inserting a piece of data into the DB, the auto-incrementing primary key ID of the piece of data is automatically returned

2.3 Parameter processing of MyBatis

2.3.1 When the parameter is single, MyBatis can be used directly without special processing

2.3.2 When there are multiple parameters, it is recommended to use @Param named parameters

2.3.3 When the parameter is entity, it is recommended to use @Param named parameter

2.3.4 When the parameter is a map, it is recommended to use @Param to name the parameter

2.4 The difference and connection between #{} and ${} in MyBatis

2.5 Detailed Explanation of Select Element

2.5.1 When the return value of myBatis is a List collection

2.5.2 When the return value of myBatis is an entity, encapsulate it into a Map

2.5.3 When the return value of myBatis is multiple entities, when encapsulating it into a Map(key=id, value=entity)

2.6 Automatic mapping of MyBatis result set

2.6.1 Non-cascading version: DAO layer interface + mapper.xml configuration file + test

2.6.2 select-resultMap-associated query-cascade attribute encapsulation

0, Maven project structure

1. The global configuration file of MyBatis: myBatis-config.xml

1.1 properties: Import external configuration files

1.1.1 Database configuration file: jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/RUNOOB?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
jdbc.username=root
jdbc.password=root

1.1.2 MyBatis global 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>

    <!--1.MyBatis可以使用properties标签来引入外部的properties配置文件:
    (1)url:引用网络路径下或者磁盘路径的资源
    (2)resource:引入类路径下的资源
    -->
    <properties resource="jdbc.properties"/>

    <!--配置MyBatis运行环境的全局配置文件-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--配置POOLED类型的JDBC数据源连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--把一个个的mapper配置文件注册到全局配置文件中-->
    <mappers>
        <mapper resource="mapper/EmployeeMapper.xml"/>
    </mappers>

</configuration>

 

1.2 settings: Set the properties of MyBatis

1.2.1 mapUnderscoreToCamelCase: Turn on automatic matching of camel case naming

    <!--2.MyBatis的设置,settings标签包含很多的设置项
    (1)name:设置项的名称
    (2)value:设置项的取值-->
    <settings>
        <!--开启在控制台打印SQL日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--开启自动的驼峰命名匹配-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

 

 

1.3 typeAlisses: the alias of the class defined in the project

    <!--3.MyBatis中entity别名的设置,这里使用的是包,也即包下的所有类都有别名了,默认的别名是类名的首字母小写-->
    <typeAliases>
        <package name="com.wind.entity"/>
    </typeAliases>

 

1.4 typeHandlers: database type and java type mapping

1.5 plugins: MyBatis plugin

1.6 environments: MyBatis configures multiple environments


    <!--4.配置MyBatis运行环境的全局配置文件-->
    <!--
    (1)environments:环境们,MyBatis可以配置多种不同的环境以提供给不同的角色使用,比如配置一个环境给开发使用【development】,再配置一个环境给测试使用【test】。
    (2)environment:每一个具体的环境信息,id 是该环境信息的唯一标识,比如配置一个环境给开发使用【development】,再配置一个环境给测试使用【test】,
        它被用在environments标签后面的default属性中。
        同时,environment必须要有两个标签:
        (2.1)transactionManager:配置数据库的事务管理器
            JDBC:JdbcTransactionFactory
            MANAGED:ManagedTransactionFactory
        (2.2)dataSource:配置数据源,有三种选择
            POOLED:PooledDataSourceFactory
            UNPOOLED:UnpooledDataSourceFactory
            JNDI:JndiDataSourceFactory
    -->
    <environments default="test">

        <!--1.给测试使用的数据源环境-->
        <environment id="test">
            <transactionManager type="JDBC"/>
            <!--配置POOLED类型的JDBC数据源连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>

        <!--2.给开发使用的数据源环境-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--配置POOLED类型的JDBC数据源连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

1.7 databaseIdProvider: MyBatis supports a variety of different database vendors

1.7.1 Different types of database vendor configuration: jdbc.properties

1.7.2 MyBatis global configuration file gives aliases to different database vendors: mybatis-config.xml

1.7.3 Environment configuration under different database environments in MyBatis global configuration file: mybatis-config.xml

1.7.4 Use different database vendor IDs in the mapper.xml file

1.7.5 The xxxMapper.xml configuration file corresponding to each table needs to be registered in the MyBatis global configuration file to be used

    <!--单个mapper注册:把一个个的mapper配置文件注册到全局配置文件中-->
    <mappers>
        <mapper resource="mapper/EmployeeMapper.xml"/>
    </mappers>

2. MyBatis mapping file

2.1 Adding, deleting, modifying and checking MyBatis

2.1.1 EmployeeTest class

import com.wind.dao.EmployeeDao;
import com.wind.entity.EmployeeEntity;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
public class EmployeeTest {

    public static void main(String[] args) {
        //1.加载MyBatis配置文件
        InputStream inputStream = EmployeeTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //2.获取实现接口的代理对象
        EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class);
        System.out.println(employeeDao);
        //增
        EmployeeEntity entity = new EmployeeEntity();
        entity.setName("小刘");
        entity.setGender("男");
        entity.setEmail("[email protected]");
        Integer addResult = employeeDao.addEmployee(entity);
        System.out.println(addResult);

        //删
        Boolean deleteResult = employeeDao.deleteEmployee(20);
        System.out.println(deleteResult);

        //改
        EmployeeEntity entity2 = new EmployeeEntity();
        entity2.setId(4);
        entity2.setName("小刘2");
        entity2.setGender("男");
        entity2.setEmail("[email protected]");
        Boolean updateResult = employeeDao.updateEmployee(entity2);
        System.out.println(updateResult);

        //查
        EmployeeEntity entity3 = employeeDao.queryEmployeeById(4);
        System.out.println(entity3);

        //提交数据
        sqlSession.commit();

        //上面那个sqlSession关闭
        sqlSession.close();
    }
}

2.1.2 EmployeeDao interface

package com.wind.dao;

import com.wind.entity.EmployeeEntity;
import org.apache.ibatis.annotations.Param;

/**
 * @Description: 这是与MyBatis中的mapper.xml文件相互绑定的接口。注意:该接口是用来操作DB的。
 */
public interface EmployeeDao {
    //增
    Integer addEmployee(@Param("entity") EmployeeEntity entity);
    //删
    Boolean deleteEmployee(@Param("id") int id);
    //改
    Boolean updateEmployee(@Param("entity") EmployeeEntity entity);
    //查
    EmployeeEntity queryEmployeeById(@Param("id") int id);
}

2.1.3 EmployeeMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--每一个mapper.xml文件都有一个命名空间,该命名空间表示:该mapper.xml文件和哪个接口绑定起来。
注意:该接口是用来操作DB的。-->
<mapper namespace="com.wind.dao.EmployeeDao">

    <insert id="addEmployee">
        insert into TBL_Employee (name, gender, email)
        values (#{entity.name}, #{entity.gender}, #{entity.email})
    </insert>

    <delete id="deleteEmployee">
        delete from TBL_Employee
        where id = #{id}
    </delete>

    <update id="updateEmployee">
        update TBL_Employee
        set name = #{entity.name}, gender = #{entity.gender}, email = #{entity.email}
        where id = #{entity.id}
    </update>

    <select id="queryEmployeeById" parameterType="int" resultType="EmployeeEntity">
        select *
        from TBL_Employee
        where id = #{id}
    </select>

</mapper>

2.1.4 Test results

2.2 When inserting a piece of data into the DB, the auto-incrementing primary key ID of the piece of data is automatically returned

2.3 Parameter processing of MyBatis

2.3.1 When the parameter is single, MyBatis can be used directly without special processing

Boolean deleteEmployee(@Param("id") int id);
    <delete id="deleteEmployee">
        delete from TBL_Employee
        where id = #{id}
    </delete>

2.3.2 When there are multiple parameters, it is recommended to use @Param named parameters

EmployeeEntity queryEmployeeByIdName(@Param("id") int id, @Param("name") String name);
    <select id="queryEmployeeByIdName" resultType="EmployeeEntity">
        select *
        from TBL_Employee
        where id = #{id} and name = #{name}
    </select>

2.3.3 When the parameter is entity, it is recommended to use @Param named parameter

Integer addEmployee(@Param("entity") EmployeeEntity entity);
   <insert id="addEmployee" keyProperty="entity.id" useGeneratedKeys="true">
        insert into TBL_Employee (name, gender, email)
        values (#{entity.name}, #{entity.gender}, #{entity.email})
    </insert>

2.3.4 When the parameter is a map, it is recommended to use @Param to name the parameter

EmployeeEntity queryEmployeeByMap(Map<String, Object> map);

//下面是测试代码
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", 4);
map.put("name", "小刘2");
EmployeeEntity employeeEntity = employeeDao.queryEmployeeByMap(map);
System.out.println(employeeEntity);
  <select id="queryEmployeeByMap" resultType="EmployeeEntity">
        select *
        from TBL_Employee
        where id = #{id} and name = #{name}
    </select>

2.4 The difference and connection between #{} and ${} in MyBatis

2.5 Detailed Explanation of Select Element

2.5.1 When the return value of myBatis is a List collection

List<EmployeeEntity> queryEmployeeByName(@Param("name") String name);

//下面是测试代码
List<EmployeeEntity> list = employeeDao.queryEmployeeByName("%小%");
System.out.println(list);
 <select id="queryEmployeeByName" resultType="com.wind.entity.EmployeeEntity">
        select *
        from TBL_Employee
        where name like #{name}
</select>

2.5.2 When the return value of myBatis is an entity, encapsulate it into a Map

Map<String, Object> queryEmployeeReturnMap(@Param("id") int id);

//下面是测试代码
Map<String, Object> objectMap = employeeDao.queryEmployeeReturnMap(1);
System.out.println(objectMap);
    <select id="queryEmployeeReturnMap" resultType="java.util.Map">
        select *
        from TBL_Employee
        where id = #{id}
    </select>

2.5.3 When the return value of myBatis is multiple entities, when encapsulating it into a Map(key=id, value=entity)

    //是多条记录的内容封装成map
    //key=EmployeeEntity的ID,value=EmployeeEntity
    //key=EmployeeEntity的name,value=EmployeeEntity也OK的
    @MapKey("id")
    Map<Integer, EmployeeEntity> queryEmployeesReturnMap(@Param("name") String name);

//下面是测试代码
        Map<Integer, EmployeeEntity> entityMap = employeeDao.queryEmployeesReturnMap("%小%");
        System.out.println(entityMap);
    <select id="queryEmployeesReturnMap" resultType="com.wind.entity.EmployeeEntity">
        select *
        from TBL_Employee
        where name like #{name}
    </select>

2.6 Automatic mapping of MyBatis result set

2.6.1 Non-cascading version: DAO layer interface + mapper.xml configuration file + test

EmployeeEntity queryEmployeeById(@Param("id") int id);
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--每一个mapper.xml文件都有一个命名空间,该命名空间表示:该mapper.xml文件和哪个接口绑定起来。
注意:该接口是用来操作DB的。-->
<mapper namespace="com.wind.dao.EmployeeDao">

    <resultMap id="myEmployeeEntity" type="com.wind.entity.EmployeeEntity">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="gender" property="gender"/>
        <result column="email" property="email"/>
    </resultMap>

    <select id="queryEmployeeById" parameterType="int" resultMap="myEmployeeEntity">
        select *
        from TBL_Employee
        where id = #{id}
    </select>

</mapper>
import com.wind.dao.EmployeeDao;
import com.wind.entity.EmployeeEntity;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EmployeeTest {

    public static void main(String[] args) {
        //1.加载MyBatis配置文件
        InputStream inputStream = EmployeeTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //2.获取实现接口的代理对象
        EmployeeDao employeeDao = sqlSession.getMapper(EmployeeDao.class);
        System.out.println(employeeDao);
        EmployeeEntity employeeEntity = employeeDao.queryEmployeeById(1);
        System.out.println(employeeEntity);

        //提交数据
        //sqlSession.commit();

        //上面那个sqlSession关闭
        sqlSession.close();
    }
}

2.6.2 select-resultMap-associated query-cascade attribute encapsulation

(1) Method 1: Cascade query

(2) Method 2: Cascade query: When an attribute of an Entity is a common field of another entity, use association

(3) Method 3: Step-by-step query: association, non-lazy loading

(4) Method 4: Step-by-step query: association, lazy loading, two new configurations are added to the global configuration file

(5) Method 5: When an attribute of Entity is a list collection, use collection

 

 

 

Guess you like

Origin blog.csdn.net/cmm0401/article/details/111731272