Mybatis的基本使用(上)

这是我参与8月更文挑战的第9天,活动详情查看:8月更文挑战

书接上回,前几天写了一篇Mybatis源码阅读的准备工作,在这篇文章里介绍了Mybatis源码的下载、以及阅读源码的准备工作。本文就在此基础上介绍一下Mybatis的基本使用。

一、引入依赖

由于是在源码项目中创建测试工程,所以不需要再引入Mybatis的依赖。而源码中为了测试方便,因此使用的Derby内嵌数据库,而我这里想使用自己的MySQL数据库,因此需要引入connector依赖。

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
复制代码

二、创建配置文件

在resources包下创建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>
    <!--指定配置文件-->
    <properties resource="resources/db.properties"/>
    <settings>
        <!--全局开启或关闭缓存,默认为true-->
        <setting name="cacheEnabled" value="false"/>
        <!--延迟加载的全局开关。可通过设置fetchType属性来覆盖该项的配置。默认值为false -->
        <setting name="lazyLoadingEnabled" value="false"/>        
    </settings>
    <!--指定扫描的包-->
    <typeAliases>
        <package name="org.apache.ibatis.z_run.pojo"/>
    </typeAliases>
    <!--环境配置-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver-class-name}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--指定Mapper.xml所在位置-->
    <mappers>
        <mapper resource="resources/xml/PurchaseMapper.xml"/>
    </mappers>
</configuration>
复制代码

这里将MySQL的配置单独拿出来形成一个配置文件db.properties,与xml文件同级。

url=jdbc:mysql://IP地址:3306/test?useSSL=false
username=用户名
password=密码
driver-class-name=com.mysql.jdbc.Driver
复制代码

三、创建POJO

以下代码省略getter/setter。

// 商品
public class Purchase {

    /**
     * ID
     */
    private Integer id;
    /**
     * 名称
     */
    private String name;
    /**
     * 价格
     */
    private Integer price;
    /**
     * 分类
     */
    private Integer category;
}

// 查询条件
public class QueryCondition {

    /**
     * ID
     */
    private Integer id;
    /**
     * 名称
     */
    private String name;
    /**
     * 价格
     */
    private Integer price;
    /**
     * 分类
     */
    private Integer category;
    private List<Integer> categoryList;
}

复制代码

四、创建Mapper接口

public interface PurchaseMapper {

    /**
     * 根据条件查询
     */
    List<Purchase> findByCondition(QueryCondition condition);

    /**
     * 根据ID查询
     */
    @Select("select * from purchase where id = #{id}")
    Purchase selectById(Integer id);

}
复制代码

五、创建Mapper.xml文件

  1. xml文件中的namespace属性需要对应Mapper接口的全限定名,以此来关联Mapper接口与xml文件。
  2. Mapper接口中的方法与xml文件中select/update/delete/insert标签的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 namespace="org.apache.ibatis.z_run.mapper.PurchaseMapper">

    <select id="findByCondition" parameterType="org.apache.ibatis.z_run.pojo.QueryCondition" resultType="org.apache.ibatis.z_run.pojo.Purchase">
        select * from purchase
        <where>
            <if test="id != null">
                and id = #{id,jdbcType=INTEGER}
            </if>
            <if test="categoryList != null and categoryList.size > 0">
                <foreach collection="categoryList" open="and category in (" close=")" item="category" separator=",">
                    ${category}
                </foreach>
            </if>
            <if test="category != null">
                and category = #{category,jdbcType=INTEGER}
            </if>
        </where>
    </select>
    
</mapper>
复制代码

六、创建数据库表

DROP TABLE IF EXISTS `purchase`;
CREATE TABLE `purchase` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  `category` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
复制代码

七、创建测试类

public class MyTest {

    @Test
    public void localDBTest1() {
        //配置文件
        String resource = "resources/mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //创建SqlSession
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            //获取Mapper接口的代理对象
            PurchaseMapper mapper = sqlSession.getMapper(PurchaseMapper.class);
            //设置查询参数
            QueryCondition queryCondition = new QueryCondition();
            List<Integer> list = new ArrayList<>();
            list.add(1);
            list.add(2);
            queryCondition.setCategoryList(list);
            //执行查询
            System.out.println(mapper.findByCondition(queryCondition));
        }
    }

}
复制代码

八、代码结构展示

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享