JAVA基础(未看)spring学习程序员

Spring学习手册(13)—— Spring整合mybatis

2017-04-05  本文已影响393人  泽_渊

Spring学习手册(12)—— Spring JDBC数据库访问我们学习了如何使用Spring的JDBC抽象进行数据库访问,这极大的简化了开发者的工作量:不需要关心数据库连接、关闭;查询语句的构造、执行......但我们依然需要使用?来占空查询参数、解析查询返回结果集。本文我们就来学习对象关系映射(Object Relational Mapping (ORM))访问数据库。本文主要学习当下较为流行的mybatis框架。

一、mybatis简介

MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
在2.0版本之前,该框架叫ibatis,后3.0版本更名为mybatis。由于Spring官方只整合了ibatis2,mybati社区为在Spring中支持mybatis,创建了mybatis-spring子项目使mybaits无缝的整合到Spring中去。

二、引入相关jar包依赖

Spring项目整合mybatis框架需要依赖mybatis和mybatis-spring jar包,因此我们需要首先添加该依赖。build.gradle文件依赖项修改如下:

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile 'mysql:mysql-connector-java:6.0.6'
    compile 'org.mybatis:mybatis:3.4.2'
    compile 'org.mybatis:mybatis-spring:1.3.1'
    compile 'org.springframework:spring-jdbc:4.3.6.RELEASE'
    compile 'org.springframework:spring-context:4.3.6.RELEASE'
}

这里mybatis版本号为3.4.2,mybatis-spring版本号为1.3.1。IDEA会自动编译项目下载依赖jiar包,当然你也可以在项目根目录下运行如下命令编译(已将gradle添加到path目录):

  gradle build

三、spring整合mybatis实战

我们添加了相关Jar包的依赖,本节我们就来展示如何在Spring中整合mybatis。
在开始代码实例之前,我们首先新建数据库score_manager(数据库名可任意命名,但需保持dataSource中URL配置根数据库名一致)、新建数据表student,表结构如下:

列名 类型
id int
name varchar(20)
gender char(1)
age int

同时我们创建Student领域模型如下:

public class Student {

    private int id;

    private String name;

    private String gender;

    private int age;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString(){
        return "["+id+","+name+","+gender+","+age+"]";
    }
}

3.1 创建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.liangwei.learnspring.dao.StudentMapper">

    <resultMap id="student" type="com.liangwei.learnspring.domain.Student">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="gender" column="gender"/>
        <result property="age" column="age"/>
    </resultMap>

    <select id="getStudentNums" resultType="int">
        select count(*) from student
    </select>

    <select id="getStudentById" resultMap="student">
        select * from student where id=#{studentId}
    </select>

    <insert id="insertStudent" parameterType="com.liangwei.learnspring.domain.Student">
        insert student
            (id,name,gender,age)
        values(
             #{id},
             #{name},
             #{gender},
             #{age})
    </insert>

    <delete id="deleteStudent" parameterType="int">
        delete from student where id = #{studentId}
    </delete>
    
    <update id="updateStudent" parameterType="com.liangwei.learnspring.domain.Student">
        update student set gender = #{gender} where id = #{id}
    </update>
</mapper>

我们使用mapper标签创建映射文件,并且使用namespace属性指定该mapper的命名空间,这里我们将命名空间设定为com.liangwei.learnspring.dao.StudentMapper,,之所以如此设置会在后面进行讲解。
我们使用resultMap标签定义了一个返回结果集的映射关系,其中idresult内部标签都是表示返回对象和数据库某列的映射关系,id指代数据库的表主键,提升mybatis运行效率。property属性表示定义领域对象的属性名称,column属性指定了数据表中的列名。定义好resultMap,mybatis就会自动为我们完成结果集和领域对象之间的互相转换。
我们分别使用insertdeleteselectupdate来定义增删查改语句,id用于唯一表示该语句,parameterType指向该语句可接受的参数,resultMap属性设置为前面使用resultMap标签设置的id值,mybatis就会自动将查询结果进行映射。

3.2 定义DataSource

<!--datasource 定义-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/score_manager"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

3.3 定义SqlSessionFactoryBean

在 MyBatis-Spring 中,我们使用SqlSessionFactoryBean来创建Session工厂,配置信息如下:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
    </bean>

dataSource属性为前面已经配置完成的DataSource,mapperLocations属性指向我们配置的SQL映射文件,这里我们设置为classpath路径下mapper文件夹下的所有以Mapper命名结尾的XML文件。

3.4 使用SqlSessionTemplate

SqlSessionTemplate类是 MyBatis-Spring 的核心。 这个类负责管理 MyBatis 的 SqlSession, 调用 MyBatis 的 SQL 方法, 翻译异常。 SqlSessionTemplate 是线程安全的, 可以被多个 DAO 所共享使用。
SqlSessionTemplate 实现了 SqlSession 接口,我们使用它来定义sqlSession,配置方式如下:

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>

其中构造器参数传入配置好的sqlSessionFactory

定义StudentDAO,接口定义如下:

public interface StudentDAO {

    Student getStudentById(int studentId);

    int getStudentNums();

    void insertStudent(Student student);

    void deleteStudent(int studentId);

    void updateStudent(Student student);
}

接口方法命名自解释,这里就不再对每个方法的意义进行解释。
对StudentDAO方式实现如下:

public class StudentDAOImpl implements StudentDAO{

    private SqlSession sqlSession;

    public Student getStudentById(int studentId) {
        return sqlSession.selectOne("getStudentById",studentId);
    }

    public int getStudentNums() {

        return  sqlSession.selectOne("getStudentNums");
    }

    public void insertStudent(Student student) {
        sqlSession.insert("insertStudent",student);
    }

    public void deleteStudent(int studentId) {
        sqlSession.delete("deleteStudent",studentId);
    }

    public void updateStudent(Student student) {
        sqlSession.update("updateStudent",student);
    }

    public void setSqlSession(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }
}

该实现持有SqlSession类型的私有属性,我们使用set方法进行注入,XML配置方式如下:

 <bean id="studentDao" class="com.liangwei.learnspring.dao.impl.StudentDAOImpl">
        <property name="sqlSession" ref="sqlSession"/>
 </bean>

以上我们使用SqlSessionTemplate完成了Spring中整合mybatis的工作,我们为每种领域对象的操作定义DAO接口并实现,我们需要为所有的DAO实现注入sqlSession。

3.5 使用SqlSessionDaoSupport(简单点)

我们使用SqlSessionTemplate极大的简化了我们对SQL的操作,但是我们依然需要为每一个实现类添加setter注入方法,当然我们可以定义基类然后让所有的DAO实现继承该基类,然后使用Spring提供的自动注入简化代码量。本节我们学习使用SqlSessionDaoSupport类,它相当于封装了SqlSessionTemplate的基类,我们只需要使用getSqlSession()来获取一个SqlSessionTemplate,剩下的操作就和SqlSessionTemplate的调用相同了。

定义StudentDAOSupport接口:

public interface StudentDAOSupport {

    Student getStudentById(int studentId);

    int getStudentNums();

    void insertStudent(Student student);

    void deleteStudent(int studentId);

    void updateStudent(Student student);

StudentDAOSupport接口实现:

public class StudentDAOSupportImpl  extends SqlSessionDaoSupport implements StudentDAOSupport {

    public Student getStudentById(int studentId) {
        return getSqlSession().selectOne("getStudentById",studentId);
    }

    public int getStudentNums() {
        return  getSqlSession().selectOne("getStudentNums");
    }

    public void insertStudent(Student student) {

        getSqlSession().insert("insertStudent",student);
    }

    public void deleteStudent(int studentId) {

        getSqlSession().delete("deleteStudent",studentId);
    }

    public void updateStudent(Student student) {
        getSqlSession().update("updateStudent",student);
    }
}

XML配置提供id为studentDaoSupport的bean:

<bean id="studentDaoSupport" class="com.liangwei.learnspring.dao.impl.StudentDAOSupportImpl">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

SqlSessionDaoSupport 需要一个 sqlSessionFactory 或 sqlSessionTemplate 属性来 设 置 。 以上我们使用显式的方式设置sqlSessionFactory属性,SqlSessionDaoSupport会使用sqlSessionFactory来创建一个SqlSessionTemplate实例,当然我们也可以使用Spring的自动注入来省去配置代码。 如 果 两 者 都 被 设 置 了 , 那 么 SqlSessionFactory 是被忽略的。

3.6 注入映射器(再简单点)

SqlSessionTemplateSqlSessionDaoSupport已明显的减少了我们关于数据操作的代码量,而mybatis提供了映射器方式,为进一步减少代码量提供了支持。mybatis使用代理类为我们简化了具体的接口实现代码。

定义映射器接口:

public interface StudentMapper {

    Student getStudentById(int studentId);

    int getStudentNums();

    void insertStudent(Student student);

    void deleteStudent(int studentId);

    void updateStudent(Student student);
}

配置映射器,使mybatis完成映射器注入:

<bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="com.liangwei.learnspring.dao.StudentMapper" />
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

我们使用org.mybatis.spring.mapper.MapperFactoryBean定义名为studentMapper的bean。需要为该bean提供mapperInterfacesqlSessionFactory属性。sqlSessionFactory我们已多次使用,这里就不过多赘述;mapperInterface为我们定义的映射器接口(一般命名使用Mapper结尾),上面例子中就是我们定义的StudentMapper接口。
这样mybatis会自动为该映射器接口创建代理,并关联相关的SQL文件定义(我们在定义sqlSessionFactory时已经明确制定要加载的SQL映射文件位置)。只需这样两步,我们完成了映射器接入工作。
⚠️如果你对我们前面定义的SQL映射文件还有印象,应该还记得mapper标签下有个namespace属性,我们设置为com.liangwei.learnspring.dao.StudentMapper,当时之所以如此设置就是为了使其支持映射器方式(目前SqlSessionTemplateSqlSessionDaoSupport方式并没有强制限制该namespace属性),如果namespace属性设置与映射器接口完全限定名不同,则会报方法为找到等类型错误。

更简单点

当我们需要配置多个映射器时,按照以上方式的配置也是会花费较多的时间精力,mybatis为我们提供了更方便的方式:使用MapperScannerConfigurer配置。它会在类路径下查找映射器,并将它们创建为MapperFactoryBean。
配置方式:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.liangwei.learnspring.dao" />
</bean>

这样它会为dao包名下的所有映射器类创建为MapperFactoryBean。当然在现实项目实践中,我们一般将包名命名为mapper结尾,如上我们可以改成com.liangwei.learnspring.dao.mapper,这样更方便我们阅读并理解维护代码。当我们需要设置多个包路径时,我们可以使用分号或逗号进行分割。

3.7 代码测试

以上我们使用不同的三种方式整合Spring和mybatis,我们定义了名为studentDaostudentDaoSupportstudentMapper的三个bean,我们可以获取它们并直接使用它们的方法,测试代码如下:

public class Application {

    public static void main(String[] args){


        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("dao.xml");


        /*  获取bean */
        StudentDAO studentDAO = applicationContext.getBean("studentDao", StudentDAO.class);

        /* 获取学生数量 */
        System.out.println(studentDAO.getStudentNums());

        /* 查找学生ID为1 的学生信息*/
        System.out.println(studentDAO.getStudentById(1));

        Student student = new Student();
        student.setId(3);
        student.setName("Jane");
        student.setGender("F");
        student.setAge(20);
        /* 插入新数据 */
        studentDAO.insertStudent(student);
        /* 查询新插入的数据,ID=3 */
        System.out.println(studentDAO.getStudentById(3));

        student.setGender("M");
        /* 更新学生数据信息,将性别改为M */
        studentDAO.updateStudent(student);
        System.out.println(studentDAO.getStudentById(3));

        /*删除studentID为3 的学生信息*/
        studentDAO.deleteStudent(3);


        /*  SqlSessionDaoSupport使用  */

        StudentDAOSupport studentDAOSupport = applicationContext.getBean("studentDaoSupport", StudentDAOSupport.class);

        System.out.println(studentDAOSupport.getStudentNums());

        System.out.println(studentDAOSupport.getStudentById(1));
        student.setGender("F");
        studentDAOSupport.insertStudent(student);
        System.out.println(studentDAOSupport.getStudentById(3));

        student.setGender("M");
        studentDAOSupport.updateStudent(student);
        System.out.println(studentDAOSupport.getStudentById(3));
        studentDAOSupport.deleteStudent(3);

        /* StudentMapper */
        StudentMapper studentMapper = applicationContext.getBean("studentMapper", StudentMapper.class);

        System.out.println(studentMapper.getStudentNums());

        System.out.println(studentMapper.getStudentById(1));

        student.setGender("F");
        studentMapper.insertStudent(student);

        System.out.println(studentMapper.getStudentById(3));
        student.setGender("M");
        studentMapper.updateStudent(student);
        System.out.println(studentMapper.getStudentById(3));

        studentMapper.deleteStudent(3);
    }
}

如上我们对每种方式的没种接口方法进行了调用,代码较为简单且结合注释很容易理解,这里我们就不更进一步解释了。
运行上述代码,我们会在控制台得到如下信息输出:

2 //数据库中学生个数
[1,Jone,F,20] //查询studentId为1 的学生信息
[3,Jane,F,20] //插入studentId为3的学生信息后的查询结果
[3,Jane,M,20]//更新了studentId为3的学生信息后的查询结果:性别更改为M
2
[1,Jone,F,20]
[3,Jane,F,20]
[3,Jane,M,20]
2
[1,Jone,F,20]
[3,Jane,F,20]
[3,Jane,M,20]

为方便理解输出信息,我们在输出信息上加了些注释,结合测试代码和注释可以更方便的理解输出结果。

代码下载

四、总结

本文我们完成了在Spring框架下mybatis的引入和整合,我们借助mybatis-spring项目使用三种不同的方式(SqlSessionTemplateSqlSessionDaoSupport映射器)完成整合工作。通过以上一步步的操作我们已经体会到mybatis的简便性、易操作性,它拆分了SQL语句和项目代码接口的依赖,减轻繁琐的数据库模版代码操作,极大的提升了程序开发人员工作效率。
完成Spring框架内整合mybatis后,我们剩下的主要工作就是定义DAO或Mapper接口,编写映射器的XML文件,mybatis官网已经给出来了较为详细的文档,大家可以到官网查看文档学习,这里也不打算写关于XML文件编写方便的语法文章了。

上一篇 下一篇

猜你喜欢

热点阅读