Mybatis代码实例

@

1、Maven导入Mybatis依赖包

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.49</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.4</version>
</dependency>

2、数据库配置文件 db.properties

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&characterEncoding=utf8
db.username=root
db.password=123456

3、Mybatis配置文件 SqlMapConfig.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>
    <!-- 一种写法,以${driver}引用,注意 & 要变成 & 详情请百度 -->
    <!--<properties>
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </properties>-->
    <!-- 引入db.properties文件配置 -->
    <properties resource="db.properties"/>
    <settings>
        <!-- 控制台打印日志,包括查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!-- 开发环境,可以配置多个,default:指定采用哪个环境 -->
    <environments default="development">
        <environment id="development">
            <!-- 事务管理器,由mybatis进行管理,事务管理类型:JDBC、MANAGED -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 数据源,池类型的数据源,类型:POOLED、UNPOOLED、JNDI -->
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 加载映射文件 mapper -->
    <mappers>
        <!-- 资源路径下 -->
        <mapper resource="mappers/table1.xml"/>
        <!-- 该方式是加载指定包下的所有映射文件 -->
        <!--<package name="com.mybatis.dao"/>-->
    </mappers>
</configuration>

4、映射文件 table1Mapper.xml

映射文件一般是放在资源文件根目录的mapper目录下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace:命名空间,随便写,一般保证命名空间唯一,用动态代理必需写接口的全限定名 -->
<mapper namespace="table1">
    <select id="findAll" resultType="com.mybatis.pojo.Table1">
        select * from table1
    </select>
</mapper>

mapper其他写法

<!-- #{}、${}都是占位符,#{}带有'',${}不带'',优先使用#{},因为后者会导致sql注入的问题 -->
<select id="selectone" resultType="com.mybatis.user.testEnpity">
    select * from user id=#{id} and title=${title}
</select>

<!-- resultMap 建立 SQL 查询结果字段与实体属性的映射关系信息 -->
<resultMap id="BaseResultMap" type="com.mybatis.student.model.Student">
    <id property="id" column="id" />
    <result column="NAME" property="name" />
    <result column="HOBBY" property="hobby" />
    <result column="MAJOR" property="major" />
    <result column="BIRTHDAY" property="birthday" />
    <result column="AGE" property="age" />
</resultMap>
<!--查询时resultMap引用该resultMap -->
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
    select id,name,hobby,major,birthday,age from student where id=#{id}
</select>

5、实体类 Table1.java

package com.database.pojo;

public class Table1 {
    private int id;
    private int col1;
    private String col2;

    public int getId() {
        return id;
    }

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

    public int getCol1() {
        return col1;
    }

    public void setCol1(int col1) {
        this.col1 = col1;
    }

    public String getCol2() {
        return col2;
    }

    public void setCol2(String col2) {
        this.col2 = col2;
    }

    @Override
    public String toString() {
        return "Table1{" +
                "id=" + id +
                ", col1=" + col1 +
                ", col2=" + col2 +
                '}';
    }
}

通常写法:接口+实现+调用

简单项目目录图
在这里插入图片描述

1、接口 Table1Dao.java
package com.mybatis.dao;

import com.mybatis.pojo.Table1;

import java.util.List;

public interface Table1Dao {
    List<Table1> findAll();
}
2、实现类 Table1DaoImpl.java
package com.mybatis.dao.impl;

import com.mybatis.dao.Table1Dao;
import com.mybatis.pojo.Table1;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class Table1DaoImpl implements Table1Dao {
    public SqlSession sqlSession;

    public Table1DaoImpl(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<Table1> findAll() {
        // 操作CRUD,第一个参数:指定statement,规则:命名空间.statementId,后面的参数是sql对应的参数
        return sqlSession.selectList("test1.findAll");
    }
}
3、调用
import com.mybatis.dao.Table1Dao;
import com.mybatis.dao.impl.Table1DaoImpl;
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;

public class Test {
    @org.junit.Test
    public void test() throws IOException {
        // 读取配置文件
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 构建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 创建
        Table1Dao table1Dao = new Table1DaoImpl(sqlSession);
        // 调用
        List<Table1> list = table1Dao.findAll();
        sqlSession.close();
    }
}

动态代理

1、接口Table1Dao.java

只需写接口,不用写实现

package com.database.mybatis.dao;

import com.database.pojo.Table1;

import java.util.List;

public interface Table1Dao {
    List<Table1> findAll();
}
2、table1Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace:动态代理必需写接口的全限定名 -->
<mapper namespace="com.database.mybatis.dao.Table1Dao">
    <select id="findAll" resultType="com.database.pojo.Table1">
        select * from table1 where 100>id
    </select>
</mapper>
3、调用
@org.junit.Test
    public void MybatisTest2() throws IOException {
        // 读取配置文件
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 构建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 创建
        Table1Dao table1Dao = sqlSession.getMapper(Table1Dao.class);
        // 调用
        List<Table1> list = table1Dao.findAll();
        sqlSession.close();
    }

动态sql

<!-- 定义sql片段,用于可重用的sql片段 -->
<sql id="whereClause">
    <!-- if标签:可以对输入的参数进行判断 -->
    <!-- test:指定判断表达式 -->
    <if test="user!=null">
        <if test="user.username!=null and user.username!=''">
            AND username LIKE '%${user.username}%'
        </if>
        <if test="user.address!=null and user.address!=''">
            AND address=#{user.address}
        </if>
    </if>
    <if test="idList!=null">
        AND id IN
        <!-- foreach标签: 可以循环传入参数值 -->
        <!-- collenction:标示pojo中集合属性的属性名称 -->
        <!-- item:每次遍历出来的对象 -->
        <!--open开始遍历时拼接的串-->
        <!--close结束遍历时拼接的串-->
        <!--separator遍历每个对象之间需要拼接字符-->
        <foreach collection="idList" item="item" open="(" close=")" separator=",">
            #{item}
        </foreach>
    </if>
</sql>

<select id="findUserList" parameterType="userVO" resultType="user">
    SELECT * FROM USER
    <!-- where标签: 默认去掉第一个AND,如果没有参数就去掉where自己-->
    <where>
        <!--引用sql语句片段-->
         <include refid="whereClause"></include>
    </where>
</select>

<!-- set标签可解决多余逗号拼接的问题 -->
<update id="updateStudent" parameterType="Object">
    UPDATE STUDENT
    <set>
        <if test="name!=null and name!='' ">
            NAME = #{name},
        </if>
        <if test="hobby!=null and hobby!='' ">
            MAJOR = #{major},
        </if>
        <if test="hobby!=null and hobby!='' ">
            HOBBY = #{hobby}
        </if>
    </set>
    WHERE ID = #{id};
</update>

<!-- trim标记是一个格式化的标记,主要用于拼接sql的条件语句(前缀或后缀的添加或忽略) -->
<!-- prefix:在trim标签内sql语句加上前缀 -->
<!-- suffix:在trim标签内sql语句加上后缀 -->
<!-- prefixOverrides:指定去除多余的前缀内容,如:prefixOverrides=“AND | OR”,去除trim标签内sql语句多余的前缀"and"或者"or" -->
<!-- suffixOverrides:指定去除多余的后缀内容 -->
<update id="updateByPrimaryKey" parameterType="Object">
    update student set 
    <trim  suffixOverrides=",">
        <if test="name != null">
            NAME=#{name},
        </if>
        <if test="hobby != null">
            HOBBY=#{hobby},
        </if>
    </trim> 
    where id=#{id}
</update>

Mybatis详细教程:https://blog.csdn.net/hellozpc/article/details/80878563

原文地址:https://www.cnblogs.com/wccw/p/12992117.html