1.环境准备
导包(jdk1.8只支持spring4.0以上的版本)
mysql驱动包
c3p0驱动包
mybatis包
spring-core、spring-aop、spring-web、spring-orm、spring-jdbc
jackson(spring对json的支持包)
mybatis_spring包
2.测试spring-mybatis整合
applicationContext.xml
<!-- 配置数据源,记得去掉myBatis-config.xml的数据源相关配置 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="user" value="root" /> <property name="password" value="juaner767" /> </bean> <!-- 配置session工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:myBatis-config.xml" /> </bean> <!-- 配置事务管理器,管理数据源事务处理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置事务通知 --> <tx:advice id="advice" transaction-manager="transactionManager"> <tx:attributes> <!-- 默认只处理运行时异常,可加rollback-for="Exception/Throwable"等处理所有异常或包括错误 --> <tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception" /> <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception" /> <tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <!-- 配置切面织入的范围,后边要把事务边界定在service层 --> <!-- 把事务边界定在service层 --> <aop:config> <aop:advisor advice-ref="advice" pointcut="execution(* com.juaner.scm.dao.impl.*.*(..))"/> </aop:config> <context:component-scan base-package="*"></context:component-scan> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
myBatis-config.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> <!-- 通过别名简化对类的使用 --> <typeAliases> <typeAlias type="com.juaner.scm.entity.Dept" alias="Dept"/> </typeAliases> <mappers> <mapper resource="com/juaner/scm/entity/DeptMapper.xml" /> </mappers> </configuration>
Dept实体及映射文件
public class Dept implements Serializable{ private Integer deptId; private String deptName; private String deptAddress; public Dept(){ } public Integer getDeptId() { return deptId; } public void setDeptId(Integer deptId) { this.deptId = deptId; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public String getDeptAddress() { return deptAddress; } public void setDeptAddress(String deptAddress) { this.deptAddress = deptAddress; } @Override public String toString() { return "Dept{" + "deptId=" + deptId + ", deptName='" + deptName + '\'' + ", deptAddress='" + deptAddress + '\'' + '}'; } }
<?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.juaner.scm.entity.DeptMapper"> <resultMap id="deptResultMap" type="Dept"> <id property="deptId" column="dept_id"/> <result property="deptName" column="dept_name"/> <result property="deptAddress" column="dept_address"/> </resultMap> <select id="selectDept" parameterType="Integer" resultMap="deptResultMap"> SELECT DEPT_ID,DEPT_NAME,DEPT_ADDRESS FROM DEPT WHERE DEPT_ID=#{deptID} </select> <insert id="insertDept" parameterType="Dept"> INSERT INTO DEPT (DEPT_NAME,DEPT_ADDRESS) VALUES (#{deptName},#{deptAddress}) </insert> </mapper>
DeptDaoImpl类
@Repository("deptDao") public class DeptDaoImpl implements DeptDao{ @Resource private SqlSessionTemplate sqlSessionTemplate; /** * 根据部门编号查询部门信息 * @param deptId 部门编号 * @return 部门信息 */ public Dept selectDept(Integer deptId){ Dept dept= sqlSessionTemplate.selectOne("com.juaner.scm.entity.DeptMapper.selectDept", deptId); return dept; } /** * 添加部门信息 * @param dept 部门信息 * @return 添加成功的记录数 */ public int insertDept(Dept dept){ System.out.println("------dao.dept:"+dept); sqlSessionTemplate.insert("com.juaner.scm.entity.DeptMapper.insertDept", dept); // int i =1/0; return 0; } }
测试
@Test public void test1(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); DeptDaoImpl deptDao = (DeptDaoImpl) context.getBean("deptDao"); Dept dept = deptDao.selectDept(1); System.out.println(dept); } @Test public void test2(){ Dept dept = new Dept(); dept.setDeptName("信息部"); dept.setDeptAddress("b3"); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); DeptDaoImpl deptDao = (DeptDaoImpl) context.getBean("deptDao"); deptDao.insertDept(dept); }
3.测试spring-mvc
web.xml
<!--配置spring监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--配置spring-mvc核心控制器--> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!--针对post请求的编码过滤器--> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!--同时开启json的支持--> <mvc:annotation-driven></mvc:annotation-driven> <context:component-scan base-package="*"/> </beans>
DeptAction
@Controller @RequestMapping("/dept") public class DeptAction { @Resource private DeptDaoImpl deptDao; @RequestMapping(value="/insert") public String insert(Dept dept){ System.out.println("---action.dept:"+dept); deptDao.insertDept(dept); return "forward:/jsp/main.jsp"; } }
index.jsp
<form action="dept/insert.action" method="post"> 名称:<input type="text" name="deptName"><br> 地址:<input type="text" name="deptAddress"><br> <input type="submit" value="ok"> </form>
main.jsp(webRoot/jsp/main.jsp)
4.优化
对service的事务控制(需要配置applicationContext.xml和spring-mvc.xml的扫描规则,否则会产生冲突无法回滚)
<!-- 把事务边界定在service层 --> <aop:config> <aop:advisor advice-ref="advice" pointcut="execution(* com.juaner.scm.service.impl.*.*(..))"/> </aop:config> <!-- 自动扫描组件,要把controller去除,他们是在spring-mvc.xml中配置,如果不去除会影响事务管理。 --> <context:component-scan base-package="com.juaner"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan>
spring-mvc扫描
<!-- 扫描所有的controller 但是不扫描service --> <context:component-scan base-package="com.juaner"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan>
去掉dao实现类
扫描basePackage下的接口,如果接口的强类名与映射文件xml中的命名空间一致,spring会生成该接口的代理对象,就不用写实现类了。
spring会用接口的强类名做命名空间,方法名做sql语句id查询map文件
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> <property name="basePackage" value="com.juaner.scm.dao"/> </bean>
映射文件
<mapper namespace="com.juaner.scm.dao.DeptDao"> <resultMap id="deptResultMap" type="Dept"> <id property="deptId" column="dept_id"/> <result property="deptName" column="dept_name"/> <result property="deptAddress" column="dept_address"/> </resultMap> <select id="selectDept" parameterType="Integer" resultMap="deptResultMap"> SELECT DEPT_ID,DEPT_NAME,DEPT_ADDRESS FROM DEPT WHERE DEPT_ID=#{deptID} </select> <insert id="insertDept" parameterType="Dept"> INSERT INTO DEPT (DEPT_NAME,DEPT_ADDRESS) VALUES (#{deptName},#{deptAddress}) </insert>
dao接口
public interface DeptDao { public Dept selectDept(Integer deptId); public int insertDept(Dept dept); }
aciton
@Autowired private DeptService deptService;
去掉myBatis-config.xml中的别名和映射文件
在applicationContext.xml中配置映射文件地址
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:myBatis-config.xml" /> <property name="mapperLocations" value="classpath:com/juaner/scm/dao/*.xml"/> </bean>
配置别名,entity下的所有类都以类名作为别名
<typeAliases> <package name="com.juaner.scm.entity"/> </typeAliases>
5.测试json
引入jackson包jackson-core-asl-1.9.11、jackson-mapper-asl-1.9.11
spring-mvc开启对json的支持
<mvc:annotation-driven></mvc:annotation-driven>
或在spring-mvc中配置json转换器
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean>
方法中添加注解@ResponseBody
@RequestMapping("/doAjax") @ResponseBody public Object doAjax(Supplier supplier){ System.out.println("-------doAjax.supplier"+supplier); supplier.setSupName("supName1"); return supplier; }
jsp方法中调用
<script type="text/javascript"> $(function(){ $("#buttonID").click( function(){ var data = {"supId":1001,"supName":"name1001"}; $.post("${proPath}/supplier/doAjax.action",data, function(json){ alert(json.supId+" "+json.supName); }); } ); }) </script>
6.抽取dao、service、action、jsp