二.十 SqlMapConfig.xml 的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="cacheEnabled" value="true"/> <!-- 控制懒加载的 --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="useGeneratedKeys" value="false"/> <setting name="autoMappingBehavior" value="PARTIAL"/> <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/> <setting name="defaultExecutorType" value="SIMPLE"/> <setting name="defaultStatementTimeout" value="25"/> <setting name="defaultFetchSize" value="100"/> <setting name="safeRowBoundsEnabled" value="false"/> <setting name="localCacheScope" value="SESSION"/> <setting name="jdbcTypeForNull" value="OTHER"/> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/> <!-- 设置日志为 log4j --> <setting name="logImpl" value="LOG4J"/> </settings> <!-- 配置别名 --> <typeAliases> <!-- 定义包的形式 ,可以多个--> <package name="com.yjl.pojo"/> </typeAliases> <!-- 放置在别名之后,环境之前 --> <plugins> <!-- 分页插件,引入拦截器 --> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 指定数据库为mysql,虽然会自动监测。 --> <property name="helperDialect" value="mysql"/> </plugin> </plugins> </configuration>
相比于以前的MyBatis的配置, 去除掉数据库配置和映射文件的配置, 由applicationContext-dao.xml 来完成。
只保留 setting,typeAliases, plugins 三个配置。
二.十一 applicationContext-dao.xml 的配置
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.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 配置数据源 ,dbcp --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxIdle" value="${jdbc.maxIdle}" /> </bean> <!-- sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 加载mybatis的全局配置文件 --> <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /> </bean> <!-- mapper扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 --> <property name="basePackage" value="com.yjl.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> </beans>
完成的工作是, 配置数据源,生成sqlSessionFactory, 配置扫描器。
二.十二 创建 UserService 接口和 UserServiceImpl 实现类
UserService 接口:
package com.yjl.service; import java.util.List; import com.yjl.pojo.User; import com.yjl.pojo.UserExample; /** @author:yuejl @date: 2019年9月9日 下午7:40:35 @Description 类的相关描述 */ public interface UserService { int countByExample(UserExample example); int deleteByExample(UserExample example); int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); List<User> selectByExample(UserExample example); User selectByPrimaryKey(Integer id); int updateByExampleSelective( User record,UserExample example); int updateByExample(User record, UserExample example); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); //根据sql语句进行相应的查询 List<User> selectBySQL(int limit, int offset); }
UserServiceImpl 实现类:
package com.yjl.service; import java.util.List; import com.yjl.pojo.User; import com.yjl.pojo.UserExample; /** @author:yuejl @date: 2019年9月9日 下午7:40:35 @Description 类的相关描述 */ public interface UserService { int countByExample(UserExample example); int deleteByExample(UserExample example); int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); List<User> selectByExample(UserExample example); User selectByPrimaryKey(Integer id); int updateByExampleSelective( User record,UserExample example); int updateByExample(User record, UserExample example); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); //根据sql语句进行相应的查询 List<User> selectBySQL(int limit, int offset); }
样式如下:
二.十三 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.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <-- 事管理器 对mybatis操作数据库事务控制,需要spri层ng使用jdbc的事务控制类 --> <!--添加扫描,需要扫描action层和service层--> <context:component-scan base-package="com.yjl"></context:component-scan> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 数据源 dataSource在applicationContext-dao.xml中配置了 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 传播行为 --> <!--列举常见的方法形式--> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="new*" propagation="REQUIRED" /> <tx:method name="set*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="change*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="count*" propagation="REQUIRED" read-only="true" /> <tx:method name="load*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" read-only="true" /> </tx:attributes> </tx:advice> <!-- aop --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.yjl.service.impl.*.*(..))"/> </aop:config> </beans>
主要是配置事务, 利用AOP的思想。
二.十四 后端UserAction
实现CRUD的操作, 注入 UserService 接口
UserAction.java
package com.yjl.action; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.yjl.pojo.User; import com.yjl.service.UserService; /** @atuhor:yuejl @Description: 类描述 */ @Controller @RequestMapping(value="/user") public class UserAction { @Autowired private UserService userService; //转到登录的页面 @RequestMapping(value="toLogin") public String toLogin(Model model){ model.addAttribute("user",new User()); return "user/login"; } //一定不要忘记添加 produces 属性。 添加时,方法为POST @RequestMapping(value="add",method=RequestMethod.POST,produces={"application/json"}) public @ResponseBody Map<String,Object> add(User user){ userService.insert(user); Map<String,Object> resultMap=new HashMap<String,Object>(); resultMap.put("request_status",true); return resultMap; } //修改时,方法为PUT @RequestMapping(value="edit/{id}",method=RequestMethod.PUT,produces={"application/json"}) public @ResponseBody Map<String,Object> edit(User user){ userService.updateByPrimaryKeySelective(user); Map<String,Object> resultMap=new HashMap<String,Object>(); resultMap.put("request_status",true); return resultMap; } //删除时,方法用DELETE @RequestMapping(value="deleteById/{id}",method=RequestMethod.DELETE,produces={"application/json"}) public @ResponseBody Map<String,Object> deleteById(@PathVariable(value="id") int id){ userService.deleteByPrimaryKey(id); Map<String,Object> resultMap=new HashMap<String,Object>(); resultMap.put("request_status",true); return resultMap; } //查询时,用GET @RequestMapping(value="findById/{id}",method=RequestMethod.GET,produces={"application/json"}) public @ResponseBody Map<String,Object> findById(@PathVariable(value="id") int id){ User user=userService.selectByPrimaryKey(id); Map<String,Object> resultMap=new HashMap<String,Object>(); resultMap.put("request_status",true); resultMap.put("user",user); return resultMap; } //查询时,用GET @RequestMapping(value="findAll",method=RequestMethod.GET,produces={"application/json"}) public @ResponseBody Map<String,Object> findAll(){ List<User> userList=userService.selectBySQL(1, 10); Map<String,Object> resultMap=new HashMap<String,Object>(); resultMap.put("request_status",true); resultMap.put("userList",userList); return resultMap; } }
二.十五 springmvc.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-- 配置的是注解的,重写视图解析器, springmvc里面只扫描action层,不能扫描其他层 --> <context:component-scan base-package="com.yjl.action"></context:component-scan> <!--配置静态资源 --> <mvc:resources location="/js/" mapping="/js/**"></mvc:resources> <mvc:resources location="/css/" mapping="/css/**"></mvc:resources> <mvc:resources location="/image/" mapping="/image/**"></mvc:resources> <!-- 设置fastjson的配置方案 --> <mvc:annotation-driven> <!-- 设置不使用默认的消息转换器 --> <mvc:message-converters register-defaults="false"> <!-- 配置Spring的转换器 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"/> <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/> <!-- 配置fastjson中实现HttpMessageConverter接口的转换器 --> <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <!-- 加入支持的媒体类型:返回contentType --> <property name="supportedMediaTypes"> <list> <!-- 这里顺序不能反,一定先写text/html,不然ie下会出现下载提示 --> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> <!-- 可添加其他的属性来扩展功能,如日期 --> <property name="features"> <list> <!-- 默认的意思就是不配置这个属性,配置了就不是默认了 --> <!-- 是否输出值为null的字段 ,默认是false--> <value>WriteMapNullValue</value> <value>WriteNullNumberAsZero</value> <value>WriteNullListAsEmpty</value> <value>WriteNullStringAsEmpty</value> <value>WriteNullBooleanAsFalse</value> <value>WriteDateUseDateFormat</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/jsp/"></property> <!-- 后缀 --> <property name="suffix" value=".jsp"></property> </bean> </beans>
配置json,和视图解析器。 如果有转换器和国际化的话,按照老蝴蝶以前讲的知识进行配置。
二.十六 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>SSM</display-name> <!-- 启动spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 乱码过滤器 --> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 隐藏域方法 --> <filter> <filter-name>hiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>hiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--前端控制 器 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 欢迎页 --> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
二.十七 前端 login.jsp 页面
采用 Ajax 进行传输数据。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="/SSM/js/jquery-2.1.1.min.js"></script> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <title>展示</title> </head> <body> <h2>两个蝴蝶飞,SSM框架整合使用</h2> <form:form commandName="user" type="post"> <button type="button" id="add" onclick="addJson()">添加</button><br/> <button type="button" id="edit" onclick="editJson()">修改</button><br/> <button type="button" id="delete" onclick="delJson()">删除</button><br/> <button type="button" id="findById" onclick="findByIdJson()">查询id></button><br/> <button type="button" id="findAll" onclick="findAllJson()">查询全部</button><br/> <div id="showId"> 展示的信息</div> </form:form> <script> function addJson(){ jsonAjax("add","add","id=10&name=精灵妹&password=1234&sex=女&age=24&description=一个快乐的精灵&_method=POST"); } function editJson(){ jsonAjax("edit","edit/10","id=10&name=精灵妹&description=一个快乐的精灵哈哈&_method=PUT"); } function delJson(){ jsonAjax("delete","deleteById/10","_method=DELETE"); } function findByIdJson(){ jsonAjax("findById","findById/10","_method=GET"); } function findAllJson(){ jsonAjax("findAll","findAll","_method=GET"); } function jsonAjax(sign,url,data){ var message=""; switch(sign){ case "add":{ message="添加成功"; break; } case "edit":{ message="修改成功"; break; } case "delete":{ message="删除成功"; break; } case "findById":{ message="查询单个成功"; break; } case "findAll":{ message="查询全部成功"; break; } } $.ajax({ type:"post", url:url, //注意请求路径 data:data, success:function(resultData){ if(resultData.request_status){ //清空 $("#showId").empty(); //追加 $("#showId").append(message+"<br/>"); if(sign=="findById"){ var data=resultData.user; var str="<table><tr><th>编号</th><th>姓名</th><th>描述</th></tr>"; str+="<tr>"; str+="<td>"+data.id+"</td>"; str+="<td>"+data.name+"</td>"; str+="<td>"+data.description+"</td>"; str+="</tr>"; str+="</table>"; $("#showId").append(str); } if(sign=="findAll"){ var data=resultData.userList; var str="<table><tr><th>编号</th><th>姓名</th><th>描述</th></tr>"; $.each(data,function(idx,item){ str+="<tr>"; str+="<td>"+item.id+"</td>"; str+="<td>"+item.name+"</td>"; str+="<td>"+item.description+"</td>"; str+="</tr>"; }) str+="</table>"; $("#showId").append(str); } } } }) } </script> </body> </html>
二.十八 重启服务器,进行验证整合是否成功
点击查询全部
点击添加,再点击查询全部
而数据库中显示 :
点击修改,再点击查询全部
数据库展示
点击查询id,显示:
说明整合成功。
二.十九 其他的配置
对 Service层的处理, 老蝴蝶是在 UserServiceImpl 实现类中添加了 @Service的注解, 然后只配置了一个 applicationContext-service.xml 的配置文件。 然后在 springmvc.xml 包扫描的时候,扫描了一下 com.yjl.service 包。
有的人, 会创建 applicationContext-service.xml 和applicationContext-tx.xml 配置文件, -service.xml 文件里面 放置各种 bean, 来实例化 UserServiceImpl 的实现类,
<!--写多个bean--> <bean id="userService" class="com.yjl.service.impl.UserServiceImpl"></bean>
-tx.xml 里面放置事务处理,即老蝴蝶这里的 applicationContext-service.xml 的内容。(这里可扫描包,也可以不扫描包)
太多,就不复制了。 即 二.十三 里面的内容。
这样,就不需要在 UserServiceImpl 上添加@Service注解了, springmvc.xml 扫描的时候,也不需要扫描 com.yjl.service包了。
两者方式都可以。
注意,在写事务的时候,一定不要捕获异常,不然事务是不会回滚的。
可以这样:
@Override public int insert(User record) { int result= userMapper.insert(record); int a=10/0; return result; }
但一定不能这样:
@Override public int insert(User record) { int result= userMapper.insert(record); try{ int a=10/0; }catch(Exception e){ e.printStackTrace(); } return result; }
谢谢!!!