spring:spring与mybatis的整合

spring与mybatis的整合

整合学习

整合的官方网站:参考文档

前提(版本需求):

MyBatis-SpringMyBatisSpring 框架Spring BatchJava
2.03.5+5.0+4.0+Java 8+
1.33.4+3.2.2+2.1+Java 6+

备注

要和 Spring 一起使用 MyBatis,需要在 Spring 应用上下文中定义至少两样东西:一个 SqlSessionFactory 和至少一个数据映射器类。

在 MyBatis-Spring 中,可使用SqlSessionFactoryBean来创建 SqlSessionFactory。要配置这个工厂 bean,只需要把下面代码放在 Spring 的 XML 配置文件中:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <property name="dataSource" ref="dataSource" />
</bean>

作用:可以使用它来执行映射了的语句,提交或回滚连接

SqlSessionFactory(创建SqlSession(用来操作数据库))有一个唯一的必要属性:用于 JDBC 的 DataSource。这可以是任意的 DataSource 对象,它的配置方法和其它 Spring 数据库连接是一样的。

重点

SqlSessionTemplate 是 MyBatis-Spring 的核心。作为 SqlSession 的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的 SqlSession(用来操作数据库)

整合所需要依赖包(使用 Maven 作为构建工具)

1、相关jar包

junit

<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.12</version>
</dependency>

mybatis

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.2</version>
</dependency>

mysql-connector-java

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
</dependency>

spring相关

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.1.10.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>5.1.10.RELEASE</version>
</dependency>

aspectJ AOP 织入器

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.9.4</version>
</dependency>

mybatis-spring整合包 【重点】

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>2.0.2</version>
</dependency>

配置Maven静态资源过滤问题!

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

整合方式一

配置文件

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
<!--    配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
<!--        关联mybatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!--    关联mybatis-->
        <property name="mapperLocations" value="classpath:com/minjiang/dao/*.xml"></property>
    </bean>
<!--    关联sqlSessionFactory-->
    <bean id = "sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--       利用构造器注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
    </bean>
<!--    实现bean-->
    <bean id="userDao" class="com.minjiang.dao.impl.UserDaoImpl">
        <property name="sqlSession" ref="sqlSession"></property>
    </bean>
</beans>

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>

</configuration>

配置实体类

public class User {
    int id;
    String name;
    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 + '\'' +
                '}';
    }
}

配置dao层

接口

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

接口mapper文件

<?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.minjiang.dao.UserMapper">
    <select id="seletAll" resultType="com.minjiang.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

接口实现类

@SuppressWarnings("all")
public class UserDaoImpl implements UserMapper {
    //sqlSession不用自己创建,spring来管理
    private SqlSessionTemplate sqlSession;
    //ioc
    public void setSqlSession(SqlSessionTemplate sqlSession){
        this.sqlSession = sqlSession;
    }

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

整合方式二

dao继承Support类 , 直接利用 getSqlSession() 获得 , 然后直接注入SqlSessionFactory . 比起方式1 , 不需要管理SqlSessionTemplate , 而且对事务的支持更加友好 . 可跟踪源码查看

SqlSessionDaoSupport

一个抽象的支持类,提供SqlSession,调用getSqlSession()方法你会得到一个getSqlSession(),用于执行sql语句

实体类

public class User {
    int id;
    String name;
    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 + '\'' +
                '}';
    }
}

dao层

接口

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

接口实现类

public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper {

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

配置文件

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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <!--    整合步骤:
            1、配置数据源
            2、配置SqlSessionFactory(同时关联关联mybatis)
            4、配置sqlSession(使用SqlSessionTemplate)
            5,实现bean(私有化SqlSession)
            -->
    <context:annotation-config/>
<!--    引入外部文件-->
    <context:property-placeholder location="classpath:db.properties" />
<!--    配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
<!--    配置SqlSessionFactory
        扩展:,SqlSessionTemplate是SqlSession的实现类,如其名,是sqlSession模板
              SqlSessionFactory也是一个接口,是SqlSession工厂,他的能力就是打开一个SqlSession会话
              SqlSessionFactoryBean是生产SqlSessionFactory的工厂bean。 -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--        需要搭载一个数据源,原因:创建的SqlSession(用来操作数据库的)-->
        <property name="dataSource" ref="dataSource"></property>
<!--        关联mybatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!--        关联mybatis的bean文件(使用注解开发可以舍弃)-->
        <property name="mapperLocations" value="classpath:com/minjiang/dao/*.xml"></property>
    </bean>
<!--    配置SqlSession(使用SqlSessionTemplate)-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sessionFactory"></constructor-arg>
    </bean>
<!--    私有化-->
    <bean id="userDao" class="com.minjiang.dao.impl.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sessionFactory" />
    </bean>
</beans>

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>

</configuration>

测试类

public class test02 {
    @Test
    public void test02(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserMapper mapper = context.getBean("userDao", UserMapper.class);
        List<User> users = mapper.selectAll();
        for (User user : users){
            System.out.println(user);
        }
    }
}
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页