整合mybatis-spring

一.整合mybatis

步骤:

第一步:导入相关的jar包:

  • junit
  • mybatis
  • mysql数据库
  • spring相关的
  • aop植入
  • mybatis-spring【新包,兼容mybatis和spring】
  <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.24</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.24</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <!--            设置正常情况的resources目录下的properties文件-->
            <resource>
                <!--                配置路径-->
                <directory>src/main/resources</directory>
                <includes>
                    <!--                    包含什么文件-->
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <!--      设置java路径的properties文件-->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

 

第二步:编写配置文件

<?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>

    <typeAliases>
        <package name="top.lostyou.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;uesUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
<mappers>
    <mapper class="top.lostyou.dao.UserMapper"/>
</mappers>
</configuration>

 

第三步:测试

接口:

package top.lostyou.dao;

import top.lostyou.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> selectUser();
}

 

mybatis的sql:

<?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">
<mapper namespace="top.lostyou.dao.UserMapper">
<select id="selectUser" resultType="User">
    SELECT * FROM mybatis.user
</select>
</mapper>

 

实体类:

package top.lostyou.pojo;

public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    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 getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

 

开启测试:

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 top.lostyou.dao.UserMapper;
import top.lostyou.pojo.User;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class myTest {
    public static void main(String[] args) throws IOException {
        String resources = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resources);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.selectUser();
        for (User user : users) {
            System.out.println(user);
        }
    }
}

 

二.mybatis-spring整合

经过了spring对mybatis的整合以后,mybatis的xml文件中绝大部分的配置都被spring给管理了,包括数据源,和注册mapper,都被spring给接管了,这样的使用过后,mybatis的功能就更加的单一化,

现在mybatis要做的就仅仅是处理数据库业务,也就是增删改查数据库,其它的配置都被spring接管了,

交给spring接管的好处就是,首先我们对于使用mybatis时连接数据库的一大堆代码都被写入了spring的配置中,就像上了模板以后方便使用,

其次,交由spring接管后,spring可以同一管理这些资源,比如更加方便注入。

<?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>

    <typeAliases>
        <package name="top.lostyou.pojo"/>
    </typeAliases>

</configuration>

 

这就是被整合之后的mybatis配置xml文件,看起来十分简洁,其实可以完全被spring接管的,但是一般不推荐,但是可以被完全接管的,比如别名(typeAliases),设置(setting)这些配置是对mybatis自己的,写在mybatis的配置文件中更好。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:aop="http://www.springframework.org/schema/aop"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!--DateSource:使用spring对的数据源替换mybatis的配置,c3p0,dbcp
    我们这里使用spring提供的jdbc:org.springframework.jdbc.datasource.DriverManagerDataSource
    -->
    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;uesUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dateSource"/>
        <!--绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:top/lostyou/dao/*.xml"/>
    </bean>
    <!--SqlSessionTemplate:就是我们使用的sqlSession-->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="userImp" class="top.lostyou.dao.UserMapperImp">
        <property name="sqlSession" ref="sqlSessionTemplate"/>
    </bean>
</beans>

 

上面是被spring整合mybatis后的xml文件,第一次看可能不懂,但是,当我们仔细去观察的时候就会发现一些与mybatis一样的东西,

首先是数据源,这是连接数据库的关键,这里只不过是使用spring提供的jdbc来连接,然而里面的 driver,url,username,password其实就是和mybatis一样的,只是换了一种spring的配置文件的写法;

然后就是连接数据库需要的工厂模式,一般是被写在了工具类中,这里我们把他写在了配置文件中,使用起来非常方便,可以被spring注入,因为spring万物皆注入;

最后就是从工厂模式(sqlSessionFactory)生产出来的对象sqlSession,用来拿取mybatis的接口,从而驱动jdbc操作数据库,只不过在spring中叫sqlSessionTemplate,Template就是模板的意思,只是换了个名字,实现的功能都是一样的。

测试:

接口:

package top.lostyou.dao;

import top.lostyou.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> selectUser();
}

 

sql——mybatis

<?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">
<mapper namespace="top.lostyou.dao.UserMapper">
<select id="selectUser" resultType="User">
    SELECT * FROM mybatis.user
</select>
</mapper>

 

mybatis配置文件:

<?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>

    <typeAliases>
        <package name="top.lostyou.pojo"/>
    </typeAliases>

</configuration>

 

spring配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:aop="http://www.springframework.org/schema/aop"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!--DateSource:使用spring对的数据源替换mybatis的配置,c3p0,dbcp
    我们这里使用spring提供的jdbc:org.springframework.jdbc.datasource.DriverManagerDataSource
    -->
    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;uesUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dateSource"/>
        <!--绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:top/lostyou/dao/*.xml"/>
    </bean>
    <!--SqlSessionTemplate:就是我们使用的sqlSession-->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="userImp" class="top.lostyou.dao.UserMapperImp">
        <property name="sqlSession" ref="sqlSessionTemplate"/>
    </bean>
</beans>

 

实现类:

package top.lostyou.dao;

import org.mybatis.spring.SqlSessionTemplate;
import top.lostyou.pojo.User;

import java.util.List;

public class UserMapperImp implements UserMapper {

    //我们所有的操作,在原来的都使用sqlSession来执行,现在都使用sqlSessionTemplate

    private SqlSessionTemplate sqlSession;

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

    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}

 

开始测试:

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 org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import top.lostyou.dao.UserMapper;
import top.lostyou.pojo.User;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class myTest {
    public static void main(String[] args) throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapper userImp = context.getBean("userImp", UserMapper.class);
        List<User> users = userImp.selectUser();
        for (User user : users) {
            System.out.println(user);
        }
    }
}

 三.整合mybatis二之SqlSessionDaoSupport

整合mybatis之二就进一步简化了我们操作,以前我们需要sqlSessionFactory来创建一个sqlSession来拿取mapper,现在我们只需要继承SqlSessionDaoSupport,就可以通过getSession()方法直接拿取到sqlSession,就不需要再spring中去拿取通过工厂模式创造,

唯一不同的就是我们再注册Bean的时候只需要再将sqlSessionFactory传入就可以了

 

 相对应的,我们再实现接口时的返回值也变得简单了很多了

 

 我们开始进行测试:

接口:

package top.lostyou.dao;

import top.lostyou.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> selectUser();
    User selectOne();
}

 

sql语句:

<?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">
<mapper namespace="top.lostyou.dao.UserMapper">
<select id="selectUser" resultType="User">
    SELECT * FROM mybatis.user
</select>
    <select id="selectOne" resultType="User">
        SELECT name FROM mybatis.user  WHERE id=1
    </select>
</mapper>

 

实现类:

package top.lostyou.dao;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import top.lostyou.pojo.User;

import java.util.List;

public class User2Mapper extends SqlSessionDaoSupport implements UserMapper {


    public List<User> selectUser() {
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }


    public User selectOne() {
        return null;
    }
}

 

spring配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:aop="http://www.springframework.org/schema/aop"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">


    <import resource="spring-dao.xml"/>
    <bean id="user2" class="top.lostyou.dao.User2Mapper">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>



</beans>

 

posted @ 2023-02-22 20:26  回忆也交给时间  阅读(31)  评论(0编辑  收藏  举报