(一)Mybatis的入门教程——HelloWorld和接口式编程

先创建一个测试表(员工表):

CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `last_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `gender` char(1) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

并添加一条测试数据:

编写javabean:

public class Employee {
    private Integer id;
    //lastName 故意和数据库中字段不一样
    private String lastName;
    private String email;
    private String gender;

    public Integer getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", gender='" + gender + '\'' +
                '}';
    }
}

接下来要实现的是,使用mybatis把数据库中的1号记录的数据查询出来,并封装成employee对象。

(1)导入jar包:

或者使用maven的方式:

以上两个方式二选一就可以了。

(2)创建MyBatis全局配置文件

从XML文件中构建一个SqlSessionFactory,因为每一个MyBatis的应用都是围绕SqlSessionFactory的实例为中心。

这部分为数据源的一些属性,从上到下依次为:驱动、地址(本地数据库地址)、用户名、密码。

将写好的sql映射文件一定要注册到全局配置文件中

(3)根据配置文件创建SqlSessionFactory对象(在测试类中创建,并且要记得导入相应的包)

public class MyBatisTest {
    /**
     * 1、根据XML配置文件(即全局配置文件)
     * @throws IOException
     */


    public void test() throws IOException {
        String resource ="mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //获取sqlSessionFactory实例,能直接执行已经映射的sql语句
        SqlSession openSession =sqlSessionFactory.openSession();

        try {
            //两个参数含义
            //sql的唯一标识符(namespace+id) 以及 执行sql要用的参数
            Employee employee = openSession.selectOne("com.dao.EmployeeMapper.selectEmp", 1);
            System.out.println(employee);
        }finally{
            openSession.close();      
        }

    }
}

(4)配置Sql映射文件

<?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.dao.EmployeeMapper">
    <!--
    namespace:名称空间(随便起名,但尽量规范易知)
    id:标签的唯一标识
    resultType:返回值类型(一般是全类名)
    #{id}:从传递过来的参数中取出id值

    -->
    <select id="selectEmp" resultType="com.beans.Employee">
        SELECT * FROM tbl_employee WHERE  id = #{id};
    </select>
</mapper>

(5)运行测试一下

发现lastName是没有值的,原因之前挖的坑,在编写javabean时,lastName故意编写的和sql数据库中的字段不一样,所以在查询的时候找不到这个字段。

所以,在编写javabean时,就要注意保证这些字段和数据库中的字段一致。

可以在Sql映射文件中,给字段起别名来完成这个字段的查询。

    <select id="selectEmp" resultType="com.beans.Employee">
        SELECT id,last_name lastName,email,gender FROM tbl_employee WHERE  id = #{id};
    </select>

这样,再测试的时候就可以完成数据的查询了:


小结:

1、根据XML配置文件(即全局配置文件)创建一个SqlSessionFactory对象,这里面包括数据源等一些运行环境信息;

2、sql映射文件,配置了每一个sql语句,以及sql的封装规则等;

3、将sql映射文件注册在全局配置文件中;

4、编写java代码,首先根据全局配置文件得到SqlSessionFactory,然后使用SqlSession工厂,获取到SqlSession对象,并使用它实现增删改查;

5、一个SqlSession就是代表和数据库的一次会话,用完需要关闭;

6、使用sql的唯一标识来告诉MyBatis执行哪个sql语句,并且每个sql语句都是保存在sql映射文件中的。


 以上是以前的使用方式,现在也可以使用接口来描述给定的sql语句的参数以及返回值等信息

(1)编写一个接口(不需要实现类):

public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
}

mybatis提供的一个功能:接口可以和映射文件动态绑定

(2)修改sql映射文件:

namespace为接口的全类名、且select标签的id改为接口中方法的id。

(3)继续测试:

 public SqlSessionFactory getSqlSessionFactory() throws IOException{
        String resource ="mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return new SqlSessionFactoryBuilder().build(inputStream);

    }

    public void test01() throws  IOException{
        //1、获取sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();

        //2、获取SqlSession对象
        SqlSession openSession =sqlSessionFactory.openSession();

        try {


            //3、获取接口的实现类对象
            //mybatis会为接口自动的创建一个代理对象,代理对象会实现增删改查方法
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);

            //4、调用接口的方法
            Employee employee = mapper.getEmpById(1);
            System.out.println(mapper.getClass());
            System.out.println(employee);
        }finally {
            openSession.close();
        }
    }

测试是正常的,且class类型是代理对象

接口式编程的好处:

接口规定的方法拥有更强的类型检查、返回值也有明确的要求;

接口本身也就是一个抽象,对于接口的实现,可以用mybatis或者hibernate等实现;

所以接口式编程也就变得十分推荐使用了。

(4)零碎知识点

SqlSession代表和数据库的依次会话,用完必须关闭

SqlSession和connection一样都是非线程安全,每次使用都应该去获取新的对象

mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象,将接口和XML文件(即sql映射文件)进行绑定

猜你喜欢

转载自blog.csdn.net/Steriles_/article/details/81557460
今日推荐