pom.xml:

 

<?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.xf</groupId>
    <artifactId>Mymybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.25</version>
        </dependency>
    </dependencies>

    <build>
        <!--解决xml没有到target-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

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>

    <typeAliases>
        <typeAlias type="com.xf.mybatis.pojo.User" alias="user"/>
    </typeAliases>
    <!-- 配置MyBatis运行环境 -->
    <environments default="development">
        <environment id="development">
            <!-- 配置JDBC事务管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- POOLED配置JDBC数据源连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://120.78.195.41:3306/test?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="***"/>
                <property name="password" value="***"/>
            </dataSource>
        </environment>
    </environments>

    <!--注册UserMapper.xml-->
    <mappers>
        <!--动态sql-->
        <mapper resource="com/xf/mybatis/mapper/UserMapperSql.xml"/>
    </mappers>
</configuration>

User:

 

package com.xf.mybatis.pojo;

public class User {
    private int id;
    private String username;
    private String password;
    private int age;

    public User() {

    }

    public User(int id, String username, String password, int age) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.age = age;
    }

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}

UserMapper.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 namespace="com.xf.mybatis.pojo.User">
    <resultMap type="user" id="userMap">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="password" column="password"/>
        <result property="age" column="age"/>
    </resultMap>


    <select id="findAll" parameterType="map" resultMap="userMap">
        select * from t_user
        <where>
            <if test="pid!=null">
                and id = #{pid}
            </if>
            <if test="pname!=null">
                and username = #{pname}
            </if>

        </where>
    </select>

    <!--set标签自动判断哪个是最后一个字段,会自动去掉最后一个,号  -->
    <update id="updateUser" parameterType="map">
        UPDATE t_user
        <set>
            <if test="username!=null">
                username=#{username},
            </if>
            <if test="password!=null">
                password=#{password},
            </if>
        </set>
        WHERE id=#{id}
    </update>
    <!--
    foreach用于迭代数组元素
    open表示开始符号
    close表示结束符号
    separator表示元素间的分隔符
    item表示迭代的数组
    collection类型,二选其一,所以parameterType="array"就不要了
    #{ids}表示数组中的每个元素值
    -->
    <delete id="deleteUser">
        DELETE from t_user where id IN

        <foreach collection="array" open="(" close=")" separator="," item="ids">
            #{ids}
        </foreach>
    </delete>

    <delete id="deleteUserList">
        DELETE from t_user where id IN

        <foreach collection="list" open="(" close=")" separator="," item="ids">
            #{ids}
        </foreach>
    </delete>


    <!--sql片段对应的字段名-->
    <sql id="key">
       /*去掉最后一个,*/
        <trim suffixOverrides=",">
        <if test="id!=null">
            id,
        </if>
        <if test="username!=null">
            username,
        </if>
        <if test="password!=null">
            password,
        </if>
        </trim>
    </sql>

    <!--sql片段对应? id属性值任意-->
    <sql id="value">
        /*去掉最后一个,*/
        <trim suffixOverrides=",">
        <if test="id!=null">
            #{id},
        </if>
        <if test="username!=null">
            #{username},
        </if>
        <if test="password!=null">
            #{ password},
        </if>
        </trim>
    </sql>

    <insert id="insertUser" parameterType="user">
        insert into t_user(<include refid="key"/>) VALUE (<include refid="value"/>)
    </insert>

</mapper>

MybatisUtils:

 

package com.xf.mybatis.utils;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/*
 * 工具类
 * @author XF
 */

public class MybatisUtil {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;

     // 加载位于src/mybatis.xml配置文件
    static{
        try {
            Reader reader = Resources.getResourceAsReader("config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

     // 禁止外界通过new方法创建
    private MybatisUtil(){}

     // 获取SqlSession
    public static SqlSession getSqlSession(){
        //从当前线程中获取SqlSession对象
        SqlSession sqlSession = threadLocal.get();
        //如果SqlSession对象为空
        if(sqlSession == null){
            //在SqlSessionFactory非空的情况下,获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession();
            //将SqlSession对象与当前线程绑定在一起
            threadLocal.set(sqlSession);
        }
        //返回SqlSession对象
        return sqlSession;
    }

     // 关闭SqlSession与当前线程分开
    public static void closeSqlSession(){
        //从当前线程中获取SqlSession对象
        SqlSession sqlSession = threadLocal.get();
        //如果SqlSession对象非空
        if(sqlSession != null){
            //关闭SqlSession对象
            sqlSession.close();
            //分开当前线程与SqlSession对象的关系,目的是让GC尽早回收
            threadLocal.remove();
        }
    }


     // 测试
    public static void main(String[] args) {
        Connection conn = MybatisUtil.getSqlSession().getConnection();
        System.out.println(conn!=null?"连接成功":"连接失败");
    }
}



UserDao:

 

 
package com.xf.mybatis.Dao;

import com.xf.mybatis.pojo.User;
import com.xf.mybatis.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.*;

public class UserDaoSql {

    /**
     * 有条件的查询所有
     */
    public List<User> findAll(int id, String name) throws Exception {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();

            Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("pid", id);
            map.put("pname", name);

            return sqlSession.selectList(User.class.getName() + ".findAll", map);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }

    /**
     * 有条件的跟新
     *
     * @param id
     * @param username
     * @param password
     */
    public void updateUser(Integer id, String username, String password) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", id);
            map.put("username", username);
            map.put("password", password);
            sqlSession.update(User.class.getName() + ".updateUser", map);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 按数组动态删除
     *
     * @param ids
     */
    public void deleteUser(int... ids) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            sqlSession.delete(User.class.getName() + ".deleteUser", ids);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }

    /**
     * 按list动态删除
     *
     * @param ids
     */
    public void deleteUserList(List<Integer> ids) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            sqlSession.delete(User.class.getName() + ".deleteUserList", ids);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }

    /**
     * 插入学生
     */
    public void insertUser(User user) throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtil.getSqlSession();
            sqlSession.insert(User.class.getName()+".insertUser",user);
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            MybatisUtil.closeSqlSession();
        }
    }


    public static void main(String[] args) throws Exception {
        UserDaoSql dao = new UserDaoSql();

        //条件查找所有
          /*  List<User> list = dao.findAll(1,null);
            for (User s : list) {
                System.out.println(s.getId() + ":" + s.getUsername());
            }*/

        //修改
        //dao.updateUser(1,null,"123456");

        //数组删除
        //dao.deleteUser(1,3,5,7);
        // dao.deleteUser(new int[]{1,3,5,7});

        //list删除
      /*  List<Integer> ids = new ArrayList<Integer>();
        ids.add(4);
        ids.add(6);
        ids.add(8);
        dao.deleteUserList(ids);*/

        //dao.insertUser(new User(1,"哈哈","123"));//insert into 表名(*,*,*) values(?,?,?)
       // dao.insertUser(new User(2,"哈哈",null));//insert into 表名(*,*) values(?,?)
        //dao.insertUser(new User(3,null,"123456"));//insert into 表名(*,*) values(?,?)
        dao.insertUser(new User(4,null,null));//insert into 表名(*) values(?)
    }

}