码迷,mamicode.com
首页 > 编程语言 > 详细

MyBatis与Spring、SpringMVC整合

时间:2016-05-13 14:48:09      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

本文主要记录MyBaits与Spring、SpringMVC的整合步骤,并且有普通的整合方式到通过利用MyBatis动态代理的方式整合的比较好的方式的一步一步演化的步骤;

1、基本环境搭建
2、整合的思路
3、第一种整合方法
4、第二种整合方法


1、基本环境搭建
Mybatis3.2.7+spring3.2.0+springmvc3.2.0
获取的方式:
1、可以通过Maven依赖进行添加;
2、可以通过在官方网站上下载MyBatis与Spring的整合包;
总结来说,jar包内容包含如下:

  • Mybatis核心和Mybatis依赖包
  • Mybatis和spring整合包
  • Spring的jar(包括springmvc的jar包)
  • 数据库驱动包
  • 第三方数据库连接池
  • JSON包(整合的时候不是必须存在,但是项目中用得较多,可以考虑添加)

2、整合的思路
步骤一:创建配置文件
以下主要结构图中的sql包在整合方法二中是不需要的,只在整合方法一中需要,特此说明。
技术分享
步骤二:理清整合思路

  • db.properties—数据库连接参数
  • log4j.properties—日志 配置文件
  • mybatis/SqlMapConfig.xml—mybatis全局配置文件
  • spring/springmvc.xml———-springmvc的全局配置文件
  • spring/applicationContext.xml—spring配置文件(配置公用内容:数据源、事务)
  • spring/ applicationContext-dao.xml—spring和mybatis整合的配置
    (SqlSessionFactory、mapper配置)
  • spring/ applicationContext-service.xml—配置业务接口

3、第一种整合方法


com.ssm.po.User

package com.ssm.po;

import java.io.Serializable;
import java.util.Date;

/**
 * User实体类
 * @author YQ
 *
 */
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    private int id;
    private String username;// 用户姓名
    private String sex;// 性别
    private Date birthday;// 出生日期
    private String address;// 地址
    private String detail;// 详细信息
    private Float score;// 成绩

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getDetail() {
        return detail;
    }
    public void setDetail(String detail) {
        this.detail = detail;
    }
    public Float getScore() {
        return score;
    }
    public void setScore(Float score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", sex=" + sex
                + ", birthday=" + birthday + ", address=" + address
                + ", detail=" + detail + ", score=" + score + "]";
    }   
}

com.ssm.dao.UserDao

package com.ssm.dao;
import com.ssm.po.User;
/**
 * 查询用户信息接口
 * @author YQ
 */
public interface UserDao {
    //根据用户id查询信息
    public User findUserById(int id) throws Exception;
}

com.ssm.dao.UserDaoImpl

package com.ssm.dao;

import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.ssm.po.User;

/**
 * 实现用户信息查询
 * @author YQ
 *
 */
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

    @Override
    public User findUserById(int id) throws Exception {
        //创建SqlSession
        SqlSession session = this.getSqlSession();
        return session.selectOne("test.findUserById",id);
    }

}

com.ssm.service.UserService

package com.ssm.service;
import com.ssm.po.User;
/**
 * 用户信息服务接口
 * @author YQ
 *
 */
public interface UserService {

    //根据id查询用户信息
    public User findUserById(int id) throws Exception;

}

com.ssm.service.UserServiceImpl

package com.ssm.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ssm.dao.UserDao;
import com.ssm.po.User;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource(name="userDao")
    private UserDao userDao;

    @Override
    public User findUserById(int id) throws Exception {
        //调用mapper查询用户信息
        return userDao.findUserById(id);
    }
}

config/mybatis/SqlMapConfig.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>
    <!-- 全局参数的配置,开启延迟加载 -->
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
        <!-- 开启二级缓存总开关 -->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    <!-- 别名的设置 -->
    <typeAliases>
        <package name="com.ssm.po"/>
    </typeAliases>
    <!-- 在sqlMapConfig.xml文件中加载user.xml文件 -->
    <mappers>
        <mapper resource="sql/user.xml"/>
    </mappers>
</configuration>

config/mybatis/applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    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-3.1.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.1.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd ">

    <context:component-scan base-package="com.ssm"></context:component-scan>

    <!-- 加载db.propertis -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 使用第三方的数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
                <property name="driverClassName" value="${db.driver}" />
        <property name="url" value="${db.url}" />
        <property name="username" value="${db.username}" />
        <property name="password" value="${db.password}" />
        <!-- 最大连接数和最大空闲连接数 -->
        <!-- 开发阶段数据库最大连接数建议设置小一点够用即可,设置为3 -->
        <property name="maxActive" value="${db.maxActive}" />
        <property name="maxIdle" value="${db.maxIdle}" />
    </bean>

    <!-- 事务管理器 -->
    <!-- 事务管理器中,mybaits使用的是jdbc的事务管理器 -->
    <bean id="transactionManager" 
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源的配置 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 通知配置 -->
    <!-- roll-back参数的配置 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 配置传播行为 -->
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!-- 切面配置 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
            pointcut="execution(* com.ssm.service.UserServiceImpl.*.*(..))"/>
    </aop:config>

</beans>

config/spring/applicationContext-dao.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    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-3.1.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.1.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd ">

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 配置SqlMapConfig.xml -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
    </bean>

    <bean id="userDao" class="com.ssm.dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean> 

</beans>

config/spring/applicationContext-service.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    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-3.1.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.1.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd ">

    <!-- 用户管理 -->
    <bean id="userService" class="com.ssm.service.UserServiceImpl"></bean>
</beans>

config/sql/user.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">

<!-- namespace命名空间特殊作用: 如果使用mapper动态代理方法,这里就需要配置mapper接口地址-->
<mapper namespace="test">
    <select id="findUserById" parameterType="int" 
        resultType="user">
        SELECT * FROM USER WHERE id = #{id}
    </select>
</mapper>

测试类

package com.ssm.test.dao.mapper;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ssm.po.User;
import com.ssm.service.UserService;

public class UserMapperTest {

    private ApplicationContext applicationContext;

    @Before
    public void setup() throws Exception {
        applicationContext = new ClassPathXmlApplicationContext(
                new String[] {"spring/applicationContext.xml",
                        "spring/applicationContext-dao.xml",
                        "spring/applicationContext-service.xml"
                }
            );
    }

    @Test
    public void testFinfUserById() throws Exception {
        UserService userService = (UserService) applicationContext.getBean("userService");
        User user = userService.findUserById(10);
        System.out.println(user);
    }

}

4、第二种整合方法
结构:
技术分享


com.ssm.action.UserAction

package com.ssm.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ssm.po.User;
import com.ssm.service.UserService;

@Controller("userAction")
@RequestMapping("/user")
public class UserAction {
    @Autowired
    private UserService userService;
    //查询用户信息
    @RequestMapping("/queryUser")
    public String queryUser(Model model, Integer id) throws Exception {

        //调用service
        User user = userService.findUserById(id);
        model.addAttribute("user",user);

        //返回逻辑视图名称
        return "queryUser";
    }
}

com.ssm.mapper.UserMapper

package com.ssm.mapper;

import com.ssm.po.User;

/**
 * UserMapper对应的接口
 * @author YQ
 *
 */
public interface UserMapper {

    //根据用户id查询用户信息
    public User findUserById(int id) throws Exception;

    //测试事务
    public void saveUser(User user) throws Exception;

    //测试事务
    public void updateUser(User user) throws Exception;
}

com.ssm.mapper.UserMapper.xml

package com.ssm.mapper;

import com.ssm.po.User;

/**
 * UserMapper对应的接口
 * @author YQ
 *
 */
public interface UserMapper {

    //根据用户id查询用户信息
    public User findUserById(int id) throws Exception;

    //测试事务
    public void saveUser(User user) throws Exception;

    //测试事务
    public void updateUser(User user) throws Exception;
}

applicationContext-dao.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    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-3.1.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.1.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd ">

    <!-- 配置SqlSessionFactory -->
    <!-- 会话工厂需要注入两个部分 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 配置SqlMapConfig.xml -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
    </bean>

    <!-- 使用mapper批量扫描器扫描mapper接口 -->
    <!-- 扫描出来的mapper会自动让spring进行注册 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 会话工厂的配置 -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        <!-- 
            扫描包路径
            多个包中阿金用半角符号隔开 
        -->
        <property name="basePackage" value="com.ssm.mapper"></property>
    </bean>

</beans>

springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    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-3.1.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.1.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd ">

    <!-- 组件扫描,扫描action -->
    <context:component-scan base-package="com.ssm"></context:component-scan>

    <!-- 处理器的映射器和适配器 -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 开放根下面的所有html文件 -->
    <mvc:resources location="/" mapping="*.*"></mvc:resources>

    <!-- 视图解析器,解析jsp视图 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 视图的前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 视图的后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <!-- 加载Spring容器 -->
    <!-- 使用通配符 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/classes/spring/applicationContext.xml,
            /WEB-INF/classes/spring/applicationContext-*.xml,
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- post乱码处理 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- contextConfigLocation指定springmvc的全局配置文件 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

效果如下:
技术分享

MyBatis与Spring、SpringMVC整合

标签:

原文地址:http://blog.csdn.net/yangqian201175/article/details/51392413

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!