第七章-spring整合mybatis

飞一样的编程
飞一样的编程
擅长邻域:Java,MySQL,Linux,nginx,springboot,mongodb,微信小程序,vue

分类: ssm 专栏: ssm框架课 标签: spring整合mybatis

2022-12-10 16:36:49 1340浏览

spring框架整合mybatis

1.基本整合方式

主要的核心步骤如下:

1.1引入jar包

1.2编写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
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url">
            <value><![CDATA[jdbc:mysql://127.0.0.1:3306/cvs_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull]]></value>
        </property>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!--配置sqlsession factory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations">
            <list>
                <value>classpath:mapper/*.xml</value>
            </list>
        </property>
    </bean>

    <!--配置sqlsessionTemplate-->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
    </bean>

    <!--配置dao-->
    <bean id="sysUserMapper" class="com.spring_study.part3.mapper.impl.SysUserMapperImpl">
        <property name="sqlSession" ref="sqlSessionTemplate"/>
    </bean>
</beans>

1.3编写dao层实现类

public class SysUserMapperImpl implements SysUserMapper {

    private SqlSessionTemplate sqlSession;

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

    @Override
    public List<SysUser> getAll() {
        return sqlSession.selectList("com.spring_study.part3.mapper.SysUserMapper.getAll");
    }
}

利用SqlSessionDaoSupport简化代码:

public class SysUserMapperImpl extends SqlSessionDaoSupport implements SysUserMapper {

  /*  private SqlSessionTemplate sqlSession;

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

    @Override
    public List<SysUser> getAll() {
        return getSqlSession().selectList("com.spring_study.part3.mapper.SysUserMapper.getAll");
    }
}
 <bean id="sysUserMapper" class="com.spring_study.part3.mapper.impl.SysUserMapperImpl">
      <!--<property name="sqlSession" ref="sqlSessionTemplate"/>-->
      <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
  </bean>

那现在我不想写dao的实现类怎么办。

  • MapperFactoryBean的方式生成代理对象
    <bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="userInfoMapper">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <property name="mapperInterface" value="com.jf3q.sm_part7.dao.UserInfoMapper"/>
    </bean>
    <bean class="com.jf3q.sm_part7.service.impl.UserInfoServiceImpl" id="userInfoService">
        <property name="userInfoMapper" ref="userInfoMapper"/>
     </bean>
  • MapperScannerConfigurer扫描的方式就是咱们这提倡的最终的方式

1.4最终版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
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url">
            <value><![CDATA[jdbc:mysql://127.0.0.1:3306/cvs_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull]]></value>
        </property>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!--配置sqlsession factory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--配置别名映射-->
        <property name="typeAliasesPackage" value="com.spring_study.part3.domain"/>
        <!--这个配置文件可以不写-->
<!--        <property name="configLocation" value="classpath:mybatis-config.xml"/>-->

        <!--如果我们的映射文件和dao层类放在同一目录下的话这部可以省略不写-->
        <property name="mapperLocations">
            <list>
                <value>classpath:mapper/*.xml</value>
            </list>
        </property>
    </bean>

    <!--配置dao-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>-->
        <property name="basePackage" value="com.spring_study.part3.mapper"/>
    </bean>

</beans>

2.映射器整合方式

不需要dao层的实现类,直接用MapperFactoryBean注入即可

<bean id="sysUserMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
      <property name="mapperInterface" value="com.spring_study.part3.mapper.SysUserMapper"/>
      <property name="sqlSessionFactory" ref="sqlSessionFactory"/>

  </bean>

简化代码:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>-->
    <property name="basePackage" value="com.spring_study.part3.mapper"/>
</bean>

3.声明式事务

3.1配置xml的方式

先导入命名空间。

<!--1.定义事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>

</bean>

<!--2.设置事务属性-->
<tx:advice transaction-manager="transactionManager" id="txAdvice">
    <tx:attributes>
        <!--带get前缀的方法不用事务管理-->
        <tx:method name="get*" read-only="true"/>
        <!--除了get前缀以外的,也就是非查询类的方法都交给事务管理-->
        
        <!--默认不配rollback-for的话是运行时异常才回滚,如果是那种sql异常 io异常之类的就不回滚了,
        所以这里配置下所有异常都回滚-->
          <tx:method name="*" rollback-for="java.lang.Exception"/>
    </tx:attributes>
</tx:advice>
<!--3.定义事务切面-->
<aop:config >
    <aop:pointcut id="serviceMethod" expression="execution(* com.spring_study.part3.service..*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
</aop:config>

3.2基于注解的方式

1.applicationContext配置文件

<!--1.定义事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>

</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>

上面的事务属性和事务切面就不用配置了

2.加注解@Transactional(rollbackFor = Exception.class)

@Service
@Transactional(rollbackFor = Exception.class)
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Override
    @Transactional(readOnly = true)
    public List<SysUser> getList() {
        return sysUserMapper.getAll();
    }

4.整合servlet

需要定义一个spring获取bean的工具类

public class SpringUtils {
    private  static  ApplicationContext app = null;

    static {
      app = new ClassPathXmlApplicationContext("applicationContext.xml");

    }

    public static <T> T getBean (Class<T> tClass){
       return app.getBean(tClass);
    }
}

servlet代码如下:

@WebServlet("/getuser")
public class UserInfoServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       req.setCharacterEncoding("utf-8");
       resp.setCharacterEncoding("utf-8");
        UserInfoService userInfoService = SpringUtils.getBean(UserInfoService.class);
        List<UserInfo> userInfoList = userInfoService.findAll();


        req.setAttribute("userInfoList",userInfoList);
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }
}

前端jso页面代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
  <head>
    <title>展示所有的用户</title>
  </head>
  <body>
  <c:if test="${userInfoList == null}">
      <c:redirect url="/getuser" />
  </c:if>
 <table border="1px">
     <th>账号</th>
     <th>真实姓名</th>
     <th>密码</th>

     <c:forEach items="${userInfoList}" var="user">
         <tr>
             <td>${user.account}</td>
             <td>${user.realName}</td>
             <td>${user.password}</td>

         </tr>
     </c:forEach>

 </table>
  </body>
</html>


补充

数据源配置destroy-method="close"的作用

将销毁连接的方法关掉,不让它断开连接,只是把Connection对象放到连接池里反复使用,这样才真正发挥了连接池的作用

好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

您可能感兴趣的博客

客服QQ 1913284695