github:https://github.com/mybatis/mybatis-3/releases

中文文档:https://mybatis.org/mybatis-3/zh/index.html

 

1. mybatis在idea的搭建

  1.新建一个maven项目,项目结构如图所示

  2.删除src目录

  3.在外部项目引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!--父工程-->
    <groupId>com.rui</groupId>
    <artifactId>MyBatis-Study</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--导入依赖-->
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>

  3.在内部项目和外部项目插入,让Maven识别资源

<!--在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

  4.在resource中编写mybatis配置文件

<?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核心配置文件-->
<configuration>
    <!--environments配置环境组-->
    <!--default默认环境-->
    <environments default="development">
        <!--environment单个环境-->
        <environment id="development">
            <!--transactionManager配置事务管理器-->
            <transactionManager type="JDBC"/>
            <!--配置连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="kodown1218"/>
            </dataSource>
        </environment>
    </environments>

</configuration>

  5.utils中编写mybatis工具类

package com.kuang.utils;

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 java.io.IOException;
import java.io.InputStream;
//sqlSessionFactory--->SessionFactory


public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try{
            //使用mybatis第一步、获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch(IOException e) {
            e.printStackTrace();
        }
    }

    //既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。
    // SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。
    // 你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

  6 pojo中编写实体

package com.kuang.pojo;

public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "user{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

  7 dao中编写接口和配置文件(保存在dao中出现问题故放在resource中了)

<?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">
<!--namespace=绑定一个对应的mapper接口-->
<mapper namespace="com.kuang.dao.UserMapper">
    <!--select查询语句-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
       /*定义sql*/
       select * from mybatis.user
   </select>

    <select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User" >
       /*定义sql*/
       select * from mybatis.user
       where id = #{id}
   </select>

    <insert id="addUser2" parameterType="map" >
       /*定义sql*/
       insert into mybatis.user(id, name, pwd) values(#{userid},#{userName},#{password});

   </insert>

    <insert id="addUser" parameterType="com.kuang.pojo.User" >
       /*定义sql*/
       insert into mybatis.user(id, name, pwd) values(#{id},#{name},#{pwd});

   </insert>

    <update id="updateUser" parameterType="com.kuang.pojo.User" >
       /*定义sql*/
       update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id};

   </update>

    <delete id="deleteUser" parameterType="int">
       /*定义sql*/
       delete from mybatis.user where id = #{id};

   </delete>
</mapper>
package com.kuang.dao;
import com.kuang.pojo.*;
import java.util.List;
import java.util.Map;
public interface UserMapper {
    //查询全部用户
    List<User> getUserList();
    //根据Id查询用户
    User getUserById(int id);
    //insert一个用户
    void addUser(User user);
    //万能map
    void addUser2(Map<String,Object> map);

    int updateUser(User user);

    void deleteUser(int id);
}

 

  8测试

package com.kuang.dao;


import com.kuang.pojo.User;
import com.kuang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;



public class UserMapperTest {
    @Test
    public void test() {
        //第一步:获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行SQL
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       // mapper.addUser(new User(4,"哈哈","123445"));
        //mapper.updateUser(new User(4,"吼吼","1233444"));
        mapper.deleteUser(4);
        sqlSession.commit();
        //        User user = mapper.getUserById(1);
//        System.out.println(user);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }

        //提交事务

        //关闭SqlSession
        sqlSession.close();
    }

    @Test
    public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("userid",4);
        map.put("userName","王五");
        map.put("password","23333");
        mapper.addUser2(map);
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

}

 

  万能map

  即用map的形式 传递参数(字段或参数过多时考虑)

 

  模糊查询

  select * from mybatis.user where name like "%"#{value}"%"