Mybatis+Spring整合

一、配置maven

  • 引入需要的包
<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</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.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
    </dependencies>
  • 配置静态资源加载目录,防止Mapper.xml无法被加载
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

二、配置Mybatis

  • 创建Mybatis配置文件 mybatis-config.xml
tu
  • 扫描包,给包下的实体类设置别名
<typeAliases>
    <package name="com.zhiyu.pojo"/>
</typeAliases>
  • 扫描包,给包下的*Mapper.xml文件注册
<mappers>
    <package name="com.zhiyu.mapper"/>
</mappers>

三、配置Spring

  • 创建一个管理Mybatis的配置文件 spring-dao.xml
image-20200426185440825
  • 引入命名空间等
<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
  • 配置数据源、SqlSessionFactory、Sqlsession
		<!--DataSource:使用Spring的数据源替换Mybatis的配置
        这里使用Spring提供的JDBC-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="cxy0920."/>
    </bean>


		<!--SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
				<!--绑定数据源-->
        <property name="dataSource" ref="dataSource" />
				<!--绑定Mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

		<!--就是我们使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
				<!--构造器注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
  • 配置事务管理器、配置事务的AOP织入
<!--配置声明式事务管理器-->
<bean id="transactionManager" 					class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>
<!--结合AOP实现事务的织入,使在调用增删查改时自动运行事务,来保持数据的一致性等-->
<!--配置事务的通知(类)(Spring管理)-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!--给哪些方法配置事务-->
    <tx:attributes>
        <tx:method name="*"/>
    </tx:attributes>
</tx:advice>

<!--配置事务切入-->
<aop:config>
    <aop:pointcut id="txPointCut" expression="execution(* com.zhiyu.service.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>

四、创建类

  • 创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}
  • 创建业务接口
public interface UserMapper {
    List<User> selectUser();
    int addUser(User user);
    int deleteUser(int id);
}
  • 使用Mapper.xml文件实现业务接口
<?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.zhiyu.mapper.UserMapper">

    <select id="selectUser" resultType="User">
    select * from user
   </select>
    
    <insert id="addUser" parameterType="user">
        insert into user (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>

    <!--这里是错的deletes-->
    <delete id="deleteUser" parameterType="_int">
        deletes from user where id = #{id}
    </delete>
</mapper>
  • 在Service层创建实现类,调用sqlSession.getMapper
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {

    @Override
    public List<User> selectUser() {

        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        mapper.addUser(new User(7,"777","777"));
        mapper.deleteUser(7);


        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }

    @Override
    public int addUser(User user) {
        return getSqlSession().getMapper(UserMapper.class).addUser(user);
    }

    @Override
    public int deleteUser(int id) {
        return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
    }
}

五、注册实现类

  • 创建配置文件 applicationContext.xml
image-20200426190210548
  • 引入spring-dao.xml
<import resource="spring-dao.xml"/>
  • 注册service层的实现类为bean,交由Spring管理
<!--注册service层实现-->
<bean id="userMapperImpl" class="com.zhiyu.service.UserMapperImpl">
    <property name="sqlSession" ref="sqlSession"/>
</bean>

<bean id="userMapperImpl2" class="com.zhiyu.service.UserMapperImpl2">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>