深入浅出Mybatis

简介    

Mybatis前身是Apache的一个开源项目ibatis,2010年迁移到了Google code并且更名为Mybatis。

2013年11月迁移到了Github。

什么时候用

    如果你需要一个灵活的可以动态生成映射关系的框架,那么Myabtis确实是一个最好的选择。相比于Hibernate的全表映射配置、不能灵活变更、难以组装复杂的sql和不能有效的支持存储过程等。Mybatis无疑弥补了这方面的很大缺陷。它拥有动态列、动态表名,支持存储过程,同时提供简易的缓存、日志级联等,更加容易适应需求变化多的项目。


开发环境搭建:

mybatis Github地址:https://github.com/mybatis/mybatis-3

mybatis框架的基本构成。

1.SqlMapConfig.xml:

全局配置文件,配置数据源、事物等,配置映射文件路径(不做掌握,在以后整合中会交由spring进行管理)

2.mapper.xml(配置sql语句)

3.SqlSessionFactory(会话工厂)

创建SqlSession

4.SqlSession会话

操作数据库(发出sql增删改查)

5.Executor执行器(是一个接口,有基本执行器和缓存执行器两个实现)

作用:SqlSession内部通过执行器操作sql

6.Sql Mapper(底层封装对象)

接收输入对象,

对操作数据库存储封装、包括sql语句、输入参数、输出结果。

输出结果类型。

下面是他们的一个简单示意图。



使用maven构建我们的项目,在pom.xml加入以下配置。

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

在resource文件夹下面新建jdbc.properties文件

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
username=root
password=root

在resource文件夹下面新建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>
    <properties resource="jdbc.properties">
    </properties>
    <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="sqlmap/userMapper.xml"/>
    </mappers>
</configuration>

在resource文件夹下面新建sqlmap文件夹,在其中在新建一个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="test">
    <select id="selectUser" parameterType="int" resultType="com.beyond.mybatis.po.User">
        select * from user WHERE id = #{id}
    </select>
</mapper>

在数据库中新建user表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  `sex` varchar(255) DEFAULT NULL,
  `addr` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8;

在其中加入几条测试数据。

然后在新建一个User类

public class User {
    private int id;
    private String username;
    private Date birthday;
    private String sex;
    private String addr;

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

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

最后编写我们的第一个测试类

public class MybatisFirst {
    /**
    *   @author:kevin
    *   @Description:   根据id查询用户信息
    *   @Date:12:08 2018/3/24
    */
    @Test
    public void findUserById() throws IOException {
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //创建会话工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //创建会话
        SqlSession sqlSession = factory.openSession();
        //通过sqlsession操作数据库
        User user = sqlSession.selectOne("test.selectUser",1);
        System.out.println(user);
        sqlSession.close();
    }
}

控制台打印user对象信息,则说明搭建成功了。




猜你喜欢

转载自blog.csdn.net/qq_21963133/article/details/79676925