大体思路:首先是配置好mybatis的环境,其次就是mybatis与spring的整合,其整合的目标是①mybatis的SqlSessionFactory交由Spring来创建②mybatis的事务交由Spring来处理;最后就是springmvc的融入,使得mybatis(dao层)、spring(中间层)、springmvc(web层)融为一体。
1、MyBatis环境配置
步骤:jar包->SQL语句->entity->dao
1.1、引入jar包
mybatis | mybatis-3.2.7.jar |
mybatis的支持包 |
asm-3.3.1.jar commons-logging-1.1.1.jar log4j-1.2.17.jar |
oracle | ojdbc5.jar |
1.2、SQL语句
OracleSQL
create table emps(eid number(1) primary key,
ename varchar2(20),
esal number(6,2),
egender varchar2(3)
);
1.3、entity
Emp.java
package com.rk.entity;public class Emp { private Integer id; private String name; private Double sal; private String gender; public Emp(){} public Emp(Integer id, String name, Double sal, String gender) { this.id = id; this.name = name; this.sal = sal; this.gender = gender; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getSal() { return sal; } public void setSal(Double sal) { this.sal = sal; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
1.4、dao
EmpDao.java
package com.rk.dao;import java.io.IOException;import java.io.Reader;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.rk.entity.Emp;public class EmpDao { private static SqlSessionFactory sqlSessionFactory; static { try { Reader reader = Resources.getResourceAsReader("mybatis.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } public void add(Emp emp)throws Exception{ SqlSession sqlSession = sqlSessionFactory.openSession(); sqlSession.insert("empNamespace.add", emp); sqlSession.commit(); sqlSession.close(); }}
1.5、mybatis的映射文件(EmpMapper.xml)和主配置文件(mybatis.xml)
EmpMapper.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="empNamespace"> <resultMap type="com.rk.entity.Emp" id="empResultMap"> <id property="id" column="eid"/> <result property="name" column="ename"/> <result property="sal" column="esal"/> <result property="gender" column="egender"/> </resultMap> <insert id="add" parameterType="com.rk.entity.Emp"> insert into emps(eid,ename,esal,egender) values(#{id},#{name},#{sal},#{gender}) </insert></mapper>
mybatis.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> <properties resource="db.properties"/> <environments default="oracle_development"> <environment id="oracle_development"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${oracle.driver}"/> <property name="url" value="${oracle.url}"/> <property name="username" value="${oracle.username}"/> <property name="password" value="${oracle.password}"/> </dataSource> </environment> <environment id="mysql_developer"> <transactionManager type="jdbc"/> <dataSource type="pooled"> <property name="driver" value="${mysql.driver}"/> <property name="url" value="${mysql.url}"/> <property name="username" value="${mysql.username}"/> <property name="password" value="${mysql.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/rk/entity/EmpMapper.xml"/> </mappers></configuration>
db.properties
#key=valueoracle.driver=oracle.jdbc.driver.OracleDriveroracle.url=jdbc:oracle:thin:@127.0.0.1:1521:orcloracle.username=scottoracle.password=tigermysql.driver=com.mysql.jdbc.Drivermysql.url=jdbc:mysql://127.0.0.1:3306/testdbmysql.username=rootmysql.password=root
1.6、测试
package com.rk.test;import org.junit.Test;import com.rk.dao.EmpDao;import com.rk.entity.Emp;public class MybatisTest { @Test public void testAdd() throws Exception { EmpDao dao = new EmpDao(); Emp emp = new Emp(1, "小明", 800D, "男"); dao.add(emp); }}
2、Mybatis与Spring整合
(1)MyBatis的SqlSessionFactory交由Spring来创建
(2)Mybatis的事务交由Spring来管理
(3)DAO、Service对象的生成和依赖注入由Spring来完成
2.1、引入需要的jar包
c3p0 | c3p0-0.9.1.2.jar |
spring-core |
commons-logging-1.2.jar (mybaits中引入了1.1.1版本,可以删除1.1.1版本) spring-beans-3.2.5.RELEASE.jar spring-context-3.2.5.RELEASE.jar spring-core-3.2.5.RELEASE.jar spring-expression-3.2.5.RELEASE.jar |
spring-aop |
aopalliance-.jar aspectjrt.jar aspectjweaver.jar spring-aop-3.2.5.RELEASE.jar |
spring-jdbc |
spring-jdbc-3.2.5.RELEASE.jar spring-tx-3.2.5.RELEASE.jar |
spring-orm | spring-orm-3.2.5.RELEASE.jar |
mybatis与spring整合的jar |
mybatis-spring-1.2.4.jar 下载地址:https://github.com/mybatis/spring/releases (版本不同带来的问题:之前引入的是mybatis-spring-1.0.0.jar,后来测试的时候发现错误,错误信息:java.lang.AbstractMethodError: org.mybatis.spring.transaction.SpringManagedTransactionFactory.newTransaction(Ljavax/sql/DataSource;Lorg/apache/ibatis/session/TransactionIsolationLevel;Z)Lorg/apache/ibatis/transaction/Transaction。换成1.2.4版本后,错误消失。) |
2.2、修改mybatis.xml
注释或者删除mybatis.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> <!-- <properties resource="db.properties"/> <environments default="oracle_development"> <environment id="oracle_development"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${oracle.driver}"/> <property name="url" value="${oracle.url}"/> <property name="username" value="${oracle.username}"/> <property name="password" value="${oracle.password}"/> </dataSource> </environment> <environment id="mysql_developer"> <transactionManager type="jdbc"/> <dataSource type="pooled"> <property name="driver" value="${mysql.driver}"/> <property name="url" value="${mysql.url}"/> <property name="username" value="${mysql.username}"/> <property name="password" value="${mysql.password}"/> </dataSource> </environment> </environments> --> <mappers> <mapper resource="com/rk/entity/EmpMapper.xml"/> </mappers></configuration>
2.3、添加Spring的主配置文件spring.xml
(1)MyBatis的SqlSessionFactory交由Spring来创建
(2)Mybatis的事务交由Spring来管理
(3)DAO、Service对象的生成和依赖注入由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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 配置C3P0连接池,目的:管理数据库连接 --><!-- <bean id="comboPooledDataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"></property> <property name="jdbcUrl" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"></property> <property name="user" value="scott"></property> <property name="password" value="tiger"></property> </bean> --> <context:property-placeholder location="classpath:db.properties"/> <bean id="comboPooledDataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${oracle.driver}"></property> <property name="jdbcUrl" value="${oracle.url}"></property> <property name="user" value="${oracle.username}"></property> <property name="password" value="${oracle.password}"></property> </bean> <!-- 配置SqlSessionFactoryBean,目的:加载mybaits配置文件和映射文件,即替代原Mybatis工具类的作用 --> <bean id="sqlSessionFactoryBeanID" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="comboPooledDataSourceID"></property> <property name="configLocation" value="classpath:mybatis.xml"></property> </bean> <!-- 配置Mybatis的事务管理器,即DataSourceTransactionManager。 因为Mybatis底层用的是JDBC事务管事器,所以在这里依然配置JDBC事务管理器 --> <bean id="dataSourceTransactionManagerID" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="comboPooledDataSourceID"></property> </bean> <!-- 配置事务通知,即让哪些方法需要事务支持 --> <tx:advice id="tx" transaction-manager="dataSourceTransactionManagerID"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- 配置事务切面,即让哪些包下的类需要事务 --> <aop:config> <aop:pointcut id="pointcut" expression="execution(* com.rk.service.*.*(..))"/> <aop:advisor advice-ref="tx" pointcut-ref="pointcut"/> </aop:config> <!-- 注册EmpDao --> <bean id="empDaoID" class="com.rk.dao.EmpDao"> <property name="sqlSessionFactory" ref="sqlSessionFactoryBeanID"></property> </bean> <!-- 注册EmpService --> <bean id="empService" class="com.rk.service.EmpService"> <property name="empDao" ref="empDaoID"></property> </bean></beans>
2.4、Dao
EmpDao.java
package com.rk.dao;import java.io.IOException;import java.io.Reader;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.rk.entity.Emp;public class EmpDao { private SqlSessionFactory sqlSessionFactory; public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } public void add(Emp emp) throws Exception{ SqlSession sqlSession = sqlSessionFactory.openSession(); sqlSession.insert("empNamespace.add", emp); sqlSession.close(); }}
2.5、Serivce
EmpService.java
package com.rk.service;import com.rk.dao.EmpDao;import com.rk.entity.Emp;public class EmpService { private EmpDao empDao; public void setEmpDao(EmpDao empDao) { this.empDao = empDao; } public void register(Emp emp) throws Exception{// int i = 1/0;// System.out.println(i); empDao.add(emp); }}
2.6、测试
package com.rk.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.rk.entity.Emp;import com.rk.service.EmpService;public class TestMybatis_Spring { @Test public void testRegister() throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml"); EmpService empService = (EmpService) ac.getBean("empService"); Emp emp = new Emp(3, "小刚", 400D, "男"); empService.register(emp); }}
3、SpringMVC的融入
3.1、引入JAR包
spring-web | spring-web-3.2.5.RELEASE.jar |
spring-webmvc | spring-webmvc-3.2.5.RELEASE.jar |
3.2、配置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" 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"> <display-name>springmvc-mybatis-oracle</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 核心springmvc核心控制器 --> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!-- 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> </web-app>
3.3、修改spring.xml
添加以下内容
<!-- 注册EmpAction --> <context:component-scan base-package="com.rk.action"/> <!-- 通知springioc容器这些注解的作用 --> <context:annotation-config/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
完整的spring.xml
<?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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 配置C3P0连接池,目的:管理数据库连接 --><!-- <bean id="comboPooledDataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"></property> <property name="jdbcUrl" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"></property> <property name="user" value="scott"></property> <property name="password" value="tiger"></property> </bean> --> <context:property-placeholder location="classpath:db.properties"/> <bean id="comboPooledDataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${oracle.driver}"></property> <property name="jdbcUrl" value="${oracle.url}"></property> <property name="user" value="${oracle.username}"></property> <property name="password" value="${oracle.password}"></property> </bean> <!-- 配置SqlSessionFactoryBean,目的:加载mybaits配置文件和映射文件,即替代原Mybatis工具类的作用 --> <bean id="sqlSessionFactoryBeanID" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="comboPooledDataSourceID"></property> <property name="configLocation" value="classpath:mybatis.xml"></property> </bean> <!-- 配置Mybatis的事务管理器,即DataSourceTransactionManager。 因为Mybatis底层用的是JDBC事务管事器,所以在这里依然配置JDBC事务管理器 --> <bean id="dataSourceTransactionManagerID" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="comboPooledDataSourceID"></property> </bean> <!-- 配置事务通知,即让哪些方法需要事务支持 --> <tx:advice id="tx" transaction-manager="dataSourceTransactionManagerID"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- 配置事务切面,即让哪些包下的类需要事务 --> <aop:config> <aop:pointcut id="pointcut" expression="execution(* com.rk.service.*.*(..))"/> <aop:advisor advice-ref="tx" pointcut-ref="pointcut"/> </aop:config> <!-- 注册EmpDao --> <bean id="empDaoID" class="com.rk.dao.EmpDao"> <property name="sqlSessionFactory" ref="sqlSessionFactoryBeanID"></property> </bean> <!-- 注册EmpService --> <bean id="empServiceID" class="com.rk.service.EmpService"> <property name="empDao" ref="empDaoID"></property> </bean> <!-- 注册EmpAction --> <context:component-scan base-package="com.rk.action"/> <!-- 通知springioc容器这些注解的作用 --> <context:annotation-config/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"/> <property name="suffix" value=".jsp"/> </bean></beans>
3.4、添加action
package com.rk.action;import javax.annotation.Resource;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.rk.entity.Emp;import com.rk.service.EmpService;@Controller@RequestMapping(value="/emp")public class EmpAction { private EmpService empService; @Resource(name="empServiceID") public void setEmpService(EmpService empService) { this.empService = empService; } @RequestMapping(value="/registerEmp") public String registerEmp(Emp emp) throws Exception{ empService.register(emp); return "success"; }}
3.5、添加index.jsp和success.jsp
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <meta name="content-type" content="text/html; charset=UTF-8"/> <title>My JSP 'index.jsp' starting page</title> </head> <body> <form action="${pageContext.request.contextPath}/emp/registerEmp.action" method="POST"> <table> <tr> <td>编号:</td> <td> <input type="text" name="id"/> </td> </tr> <tr> <td>姓名:</td> <td> <input type="text" name="name"/> </td> </tr> <tr> <td>薪水:</td> <td> <input type="text" name="sal"/> </td> </tr> <tr> <td>性别:</td> <td> <input type="radio" name="gender" value="男"/>男 <input type="radio" name="gender" value="女" checked="checked"/>女 </td> </tr> <tr> <td colspan="2"> <input type="submit" value="注册"/> </td> </tr> </table> </form> </body></html>
/jsp/success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <meta name="content-type" content="text/html; charset=UTF-8"/> <title>success page</title> </head> <body> success <br> </body></html>