欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MyBatis-Spring整合

程序员文章站 2022-07-10 09:11:01
导入相关依赖:mybatismysql数据库Spring相关的AOP置入mybatis-springjunit测试相关的 org.mybatis ...

导入相关依赖:

  • mybatis
  • mysql数据库
  • Spring相关的
  • AOP置入
  • mybatis-spring
  • junit测试相关的
        <!--整合Mybatis-Spring要是用的依赖-->
        <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--mysql连接数据库依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--spring-ioc依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <!--AOP依赖,独立的AOP框架,与spring框架一起使用-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <!--使用spring操作数据库-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <!--MyBatis-Spring-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
        <!--测试相关依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

编写Mybatis步骤:
1,编写核心配置文件
2,编写工具类
3,编写实体类
4,编写接口
5,编写Mapper.xml
6,测试


Mybatis相关操作传送门:第一个Mybatis程序


MyBatis-Spring整合

第一步:编写核心配置文件(Mybatis数据库环境配置)
mybatis-config.xml

<configuration>
	......
    <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;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    ......
</configuration>

将Mybatis数据库环境配置中的数据源dataSource注入Spring配置文件中,由Spring管理:
applicationContext.xml

    <!--注入数据源-->
    <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/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

第二步:编写工具类
MybatisUtils.java

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resources = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resources);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

MybatisUtils.java这个工具类创建了两个对象,sqlSessionFactorysqlSession
同样,这两个对象由Spring来接管:

<!--SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定mybatis配置文件地址,可以添加注册映射-->
    </bean>
<!--SqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

MyBatis-Spring整合

从源码中可以看到:从SqlSessionFactoryBean类中可以获得SqlSessionFactory的对象,这个类的属性中有DataSource dataSource属性,就做了数据源的注入
MyBatis-Spring整合
Spring中的SqlSessionTemplate的功能与Mybatis中的SqlSession具有同样的功能,所以要获得SqlSessionTemplate对象要通过传入一个参数SqlSessionFactory的的构造器来获得。
第三步:编写实体类
User.java

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 + '\'' +
                '}';
    }
}

第四步:编写接口:
UserMapper.java

public interface UserMapper {
    //查询全部用户
    public List<User> queryUser();
}

第五步:编写Mapper.xml文件

<?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="com.mofei.mapper.UserMapper">
    <select id="queryUser" resultType="USer">
        select * from mybatis.user
    </select>
</mapper>

之后,在Mybatis核心配置文件(mybatis-config.xml)中注册映射以及User类的全类名的别名

	<typeAliases>
        <typeAlias type="com.mofei.pojo.User" alias="User"/>
    </typeAliases>
    ......
	<mappers>
        <mapper class="com.mofei.mapper.UserMapper"/>
    </mappers>

同样,将注册映射注入到Spring配置文件中,由Spring来接管,留一个别名配置在Mybatis配置文件中,见证Mybatis-Spring整合,当然也可以不要别名,然而Mybatis配置文件就空了,配置内容被Spring全部接管。

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定mybatis配置文件地址,可以添加注册映射(*.xml:将包中的xml文件全部注册映射)-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/mofei/mapper/*.xml"/>
    </bean>

此时,除了事务之外,Mybatis核心配置文件中的内容都被Spring接管了,由于SqlSession写入了配置文件,变成了面向对象的,所以Spring还要创建一个实现类,去实现Mapper接口,以后就可以直接通过这个类去调用其中的方法
UserMapperImpl.java

public class UserMapperImpl implements UserMapper{
    //之前操作,都使用SqlSession来执行,现在换成SqlSessionTemplate
    private SqlSessionTemplate sqlSession;

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

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

然后将这个类及属性注入到Spring配置文件中:

    <bean id="UserMapperImpl" class="com.mofei.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

进行测试:

public class MyTest {
    @Test
    public void queryUserTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper mapper = context.getBean("UserMapperImpl", UserMapper.class);
        List<User> users = mapper.queryUser();
        for (User user : users) {
            System.out.println(user);
        }
    }
}

测试结果:

User{id=1, name='叶不羞', pwd='yebuxiu'}
User{id=2, name='提莫', pwd='timo'}
User{id=3, name='黄少天', pwd='huangshaotian'}
User{id=4, name='寒烟柔', pwd='yanrou'}
User{id=5, name='君不笑', pwd='junmoxiao'}
User{id=6, name='荷花', pwd='hehua'}

就是把Mybatis中的核心配置文件都注入到Spring的配置文件中

下图为mybatis的目录结构:
MyBatis-Spring整合
下图为spring整合mybatis后的目录结构:
MyBatis-Spring整合

整体整合顺序:

第一步:整合Mybatis核心配置文件(mybatis-config.xml)及工具类(MybatisUtils.java),其中包括:数据源配置,SqlSessionFactory以及SqlSessionTemplate

applicationContext.xml

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

    <!--注入数据源-->
    <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/mybatis?useSSL=false&amp;useUnicode=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="dataSource"/>
        <!--绑定mybatis配置文件地址,可以添加注册映射(*.xml:将包中的xml文件全部注册映射)-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/mofei/mapper/*.xml"/>
    </bean>
    <!--SqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    <!--注入接口实现类的对象及属性-->
    <bean id="UserMapperImpl" class="com.mofei.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>
</beans>

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>
    <typeAliases>
        <typeAlias type="com.mofei.pojo.User" alias="User"/>
    </typeAliases>
</configuration>

第二步:编写实体类(User.java)

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

第三步:编写接口(UserMapper.java)

public interface UserMapper {
    //查询全部用户
    public List<User> queryUser();
}

第四步:编写Mapper.xml

<mapper namespace="com.mofei.mapper.UserMapper">
    <select id="queryUser" resultType="USer">
        select * from mybatis.user
    </select>
</mapper>

第五步:添加接口实现类

public class UserMapperImpl implements UserMapper{
    //之前操作,都使用SqlSession来执行,现在换成SqlSessionTemplate
    private SqlSessionTemplate sqlSession;

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

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

第五步:测试

public class MyTest {
    @Test
    public void queryUserTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper mapper = context.getBean("UserMapperImpl", UserMapper.class);
        List<User> users = mapper.queryUser();
        for (User user : users) {
            System.out.println(user);
        }
    }
}

Mybatis-Spring参考文档:mybatis-spring官方文档


资源过滤:

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

本文地址:https://blog.csdn.net/mofeigege/article/details/110223632