本文主要記錄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>
效果如下: