一、安装mybatis

 

要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于类路径(classpath)中即可。

如果使用 Maven 来构建项目,则需将下面的依赖代码置于 pom.xml 文件中:

<dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.9</version>
    </dependency>

二、XML 配置文件

一、mybatis-config.xml

Mybatis的数据源配置文件包含数据库驱动、数据库连接地址、用户名密码、事务管理等,还可以配置连接池的连接数、空闲时间等,一个mybatis-config.xml基本的配置信息如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

二、mybatis mapper文件映射 

①使用相对于类路径的资源引用

<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
</mappers>

②使用映射器接口实现类的完全限定类名

<!-- 使用映射器接口实现类的完全限定类名
	mybais去加载class对应的接口,然后还会去加载该接口同目录下的同名xml文件 
-->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
</mappers>

③将包内的映射器接口实现全部注册为映射器

<!-- 将包内的映射器接口实现全部注册为映射器   
 使用package元素批量注册Mapper接口
  1.包名和接口所在的包名字一致
  2.mapper文件的名字和接口的名字一致
  3.创建包是使用/分割
-->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

三、设置资源文件路径

Maven中默认是只会打包resource下的资源文件。如果我们的文件不放在resource, 则需要通过配置告知Maven

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
    </resource>
     <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
          <include>**/*.tld</include>
        </includes>
        <filtering>false</filtering>
      </resource>
</resources>

四、SQL映射文件

一个简单实例如下:

<?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 namespace="命名空间">

<select id="方法名" resultMap="返回值类型" parameterType="参数类型">

-- sql语句

</select>

</mapper>

五、会话工厂与会话

Mybatis中会话工厂SqlSessionFactory类可以通过加载资源文件,读取数据源配置mybatis-config.xml信息,从而产生一种可以与数据库交互的会话实例SqlSession,会话实例SqlSession根据Mapper.xml文件中配置的sql,对数据库进行操作。

六、运行流程

会话工厂SqlSessionFactory通过加载资源文件获取MapConfig.xml配置文件信息,然后生成可以与数据库交互的会话实例SqlSession。会话实例可以根据Mapper配置文件中的Sql配置去执行相应的增删改查操作

执行流程图:

mybatis plus maven配置_maven

三、mybatis实现增删改查

一、UserMapper.xml

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

    <insert id="add" parameterType="com.bhf.mybatis.entity.User">
        insert into user(username,password)values(#{username},#{password})
    </insert>
    <select id="selectAll" resultType="com.bhf.mybatis.entity.User">
        select * from user
    </select>
    <delete id="deleteById" parameterType="integer">
        delete from user where id = #{id}
    </delete>
    <!--
       sq语句的获取的参数列表是两个或以上参数 (username,password)
       异常信息:Available parameters are [arg1, arg0, param1, param2]
       解决方法 :
        1. 获取参数时  根据参数顺序 使用 param1  param2
        2.使用@Param注解 指定获取参数的标识
        3.将参数封装成实例对象   User
        4.将参数封成map集合    key :value  获取参数的标识  key
    -->
    <insert id="addUser" >
        insert into user(username,password)values(#{username},#{password})
    </insert>


    <insert id="addUser2" >
        insert into user(username,password)values(#{username},#{password})
    </insert>

</mapper>

二、UserMapper

package com.bhf.mybatis.mapper;

import com.bhf.mybatis.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface UserMapper {
    Integer add(User user);
    List<User> selectAll();
    Integer deleteById(Integer id);

    Integer addUser(@Param("username") String username, @Param("password") String password);

    Integer addUser2(Map<String,String> map);
}

三、测试类

package com.bhf.mybatis;

import static org.junit.Assert.assertTrue;

import com.bhf.mybatis.entity.User;
import com.bhf.mybatis.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

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

/**
 * Unit test for simple App.
 */
public class AppTest {
    private SqlSessionFactory sqlSessionFactory;
    @Before
    public void init(){
        try {
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 测试新增,封装
     */
    @Test
    public void test01(){
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        System.out.println("mapper = " + mapper);
        User user = new User();
        user.setUsername("root");
        user.setPassword("123456");
        Integer add = mapper.add(user);
        System.out.println("add = " + add);
    }

    /**
     * 测试查询
     */
    @Test
    public void test02(){
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        System.out.println("mapper = " + mapper);
        List<User> users = mapper.selectAll();
        System.out.println("users = " + users);
}

    /**
     * 测试删除
     */
    @Test
    public void test03(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        System.out.println("mapper = " + mapper);
        Integer integer = mapper.deleteById(739266618);
    }

    /**
     * 测试新增,多参数
     */
    @Test
    public void test04(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        System.out.println("mapper = " + mapper);
        Integer root2 = mapper.addUser("root2", "123456");
        System.out.println("root2 = " + root2);
    }

    /**
     * 测试新增,使用map集合
     */
    @Test
    public void test05(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        System.out.println("mapper = " + mapper);
        HashMap<String,String> map = new HashMap<>();
        map.put("username","root3");
        map.put("password","123456");
        Integer root3 = mapper.addUser2(map);
        System.out.println("root3 = " + root3);
    }
}

mybatis中使用log4j日志工具

1.配置mybatis-config.xml

<!--    开启日志-->
 <setting name="logImpl" value="LOG4J"/>

开启驼峰命名

<!--    设置驼峰命名-->
 <setting name="mapUnderscoreToCamelCase" value="true"/>

设置别名

<typeAliases>
    <!--设置别名-->
    <package name="cn.kgc.mybatis.pojo"/>
</typeAliases>

2.配置log4j.properties文件,放置在resources目录下

log4j.rootLogger=DEBUG,Console

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

log4j.logger.org.apache=ERROR
log4j.logger.org.mybatis=ERROR
log4j.logger.org.springframework=ERROR

#这个需要
log4j.logger.log4jdbc.debug=ERROR
log4j.logger.com.gk.mapper=ERROR
log4j.logger.jdbc.audit=ERROR
log4j.logger.jdbc.resultset=ERROR
#这个打印SQL语句非常重要
log4j.logger.jdbc.sqlonly=DEBUG
log4j.logger.jdbc.sqltiming=ERROR
log4j.logger.jdbc.connection=FATAL