Spring+SpringMVC+MyBatis整合实战(SSM框架)

目录

  • SpringMVC
  • Spring
  • MyBatis
  • 项目结构
  • maven配置文件pom.xml
  • webapp配置文件web.xml
  • spring配置文件applicationContext.xml
  • spring-mvc配置文件spring-mvc.xml
  • mybatis映射文件AccountMapper.xml
  • mybatis配置文件(两种整合方法)
  • 日志配置文件log4j.properties
  • 建表语句
  • Tomcat传递过程
在写代码之前我们先了解一下这三个框架分别是干什么的?

SpringMVC 它用于web层,相当于controller(等价于传统的servlet和struts的action),用来处理用户请求。举个例子,用户在地址栏输入http://网站域名/login,那么springmvc就会拦截到这个请求,并且调用controller层中相应的方法,(中间可能包含验证用户名和密码的业务逻辑,以及查询数据库操作,但这些都不是springmvc的职责),最终把结果返回给用户,并且返回相应的页面(当然也可以只返回json/xml等格式数据)。springmvc就是做前面和后面过程的活,与用户打交道!!

Spring 太强大了,以至于我无法用一个词或一句话来概括它。但与我们平时开发接触最多的估计就是IOC容器,它可以装载bean(也就是我们java中的类,当然也包括service dao里面的),有了这个机制,我们就不用在每次使用这个类的时候为它初始化,很少看到关键字new。另外spring的aop,事务管理等等都是我们经常用到的。

MyBatis 如果你问我它跟鼎鼎大名的Hibernate有什么区别?我只想说,他更符合我的需求。第一,它能自由控制sql,这会让有数据库经验的人(当然不是说我啦~捂脸~)编写的代码能搞提升数据库访问的效率。第二,它可以使用xml的方式来组织管理我们的sql,因为一般程序出错很多情况下是sql出错,别人接手代码后能快速找到出错地方,甚至可以优化原来写的sql。

项目结构 Spring+SpringMVC+MyBatis整合实战(SSM框架)
文章图片


maven配置文件pom.xml
4.0.0com.neuspring-over1.0-SNAPSHOTwarspring-over Maven Webapphttp://www.example.comUTF-81.81.8org.springframeworkspring-context5.0.5.RELEASEorg.aspectjaspectjweaver1.8.7org.springframeworkspring-jdbc5.0.5.RELEASEorg.springframeworkspring-tx5.0.5.RELEASEorg.springframeworkspring-test5.0.5.RELEASEorg.springframeworkspring-webmvc5.0.5.RELEASEjavax.servletservlet-api2.5javax.servlet.jspjsp-api2.0org.mybatismybatis3.4.5org.mybatismybatis-spring1.3.1mysqlmysql-connector-java5.1.44c3p0c3p00.9.1.2junitjunit4.12jstljstl1.2sprig-overmaven-clean-plugin3.0.0maven-resources-plugin3.0.2maven-compiler-plugin3.7.0maven-surefire-plugin2.20.1maven-war-plugin3.2.0maven-install-plugin2.5.2maven-deploy-plugin2.8.2


webapp配置文件web.xml
contextConfigLocationclasspath:applicationContext.xmlorg.springframework.web.context.ContextLoaderListenerDispatcherServletorg.springframework.web.servlet.DispatcherServletcontextConfigLocationclasspath:spring-mvc.xml1DispatcherServlet/CharacterEncodingFilterorg.springframework.web.filter.CharacterEncodingFilterencodingUTF-8CharacterEncodingFilter/*


spring配置文件applicationContext.xml


spring-mvc配置文件spring-mvc.xml


mybatis映射文件AccountMapper.xml
insert into account(id,name,money) values(#{id},#{name},#{money})select * from account


mybatis配置文件(两种整合方法) 1.sqlMapConfig.xml直接引入

引入方法
public void save(Account account) {try {//加载配置文件InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); //构建会话工厂SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); //创建连接SqlSession sqlSession = sqlSessionFactory.openSession(); //获取映射对象AccountMapper mapper = sqlSession.getMapper(AccountMapper.class); //执行方法mapper.save(account); //提交连接sqlSession.commit(); //关闭连接sqlSession.close(); } catch (IOException exception) {exception.printStackTrace(); }}

2.sqlMapConfig-spring.xml使用spring构建连接
sqlMapConfig-spring.xml

spring配置注入

注入代码
@Autowiredprivate AccountMapper accountMapper; @Overridepublic void save(Account account) {accountMapper.save(account); }


日志配置文件log4j.properties
## Hibernate, Relational Persistence for Idiomatic Java## License: GNU Lesser General Public License (LGPL), version 2.1 or later.# See the lgpl.txt file in the root directory or .#### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.errlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file hibernate.log ####log4j.appender.file=org.apache.log4j.FileAppender#log4j.appender.file.File=hibernate.log#log4j.appender.file.layout=org.apache.log4j.PatternLayout#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###log4j.rootLogger=all, stdout


建表语句
create table account( id int primary key auto_increment, name varchar(100), money double(7,2))


Tomcat传递过程 1.网页获取表单
save.jsp
Title - 锐客网添加账户信息表单
账户名称:
账户金额:


Spring+SpringMVC+MyBatis整合实战(SSM框架)
文章图片


2.Controller层处理请求
AccountController.java
package com.neu.controller; import com.neu.domain.Account; import com.neu.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import java.util.List; @Controller@RequestMapping("/account")public class AccountController {@Autowiredprivate AccountService accountService; @RequestMapping(value = "https://www.it610.com/save",produces = "text/html; charset=UTF-8")@ResponseBodypublic String save(Account account){accountService.save(account); System.out.println(account); return "保存成功"; }@RequestMapping("/findAll")public ModelAndView findAll(){List accountList = accountService.findAll(); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("accountList",accountList); modelAndView.setViewName("accountList"); return modelAndView; }}

3.service层处理业务逻辑
AccountServiceimpl.java
package com.neu.service.impl; import com.neu.domain.Account; import com.neu.mapper.AccountMapper; import com.neu.service.AccountService; 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 org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.List; @Service("accountService")public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountMapper accountMapper; @Overridepublic void save(Account account) {//try {////加载配置文件//InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); ////构建会话工厂//SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); ////创建连接//SqlSession sqlSession = sqlSessionFactory.openSession(); ////获取映射对象//AccountMapper mapper = sqlSession.getMapper(AccountMapper.class); ////执行方法//mapper.save(account); ////提交连接//sqlSession.commit(); ////关闭连接//sqlSession.close(); //} catch (IOException exception) {//exception.printStackTrace(); //}accountMapper.save(account); }@Overridepublic List findAll() {//try {//InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); //SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); //SqlSession sqlSession = sqlSessionFactory.openSession(); //AccountMapper mapper = sqlSession.getMapper(AccountMapper.class); //List accountList = mapper.findAll(); //sqlSession.close(); //return accountList; //} catch (IOException exception) {//exception.printStackTrace(); //}return accountMapper.findAll(); }}

4.mapper与数据库交互
mapper层对数据库进行数据持久化操作,他的方法语句是直接针对数据库操作的,主要实现一些增删改查操作,在mybatis中方法主要与与xxx.xml内相互一一映射
AccountMapper.java
package com.neu.mapper; import com.neu.domain.Account; import java.util.List; public interface AccountMapper {public void save(Account account); public List findAll(); }

【Spring+SpringMVC+MyBatis整合实战(SSM框架)】到此这篇关于Spring+SpringMVC+MyBatis整合实战(SSM框架)的文章就介绍到这了,更多相关Spring SpringMVC MyBatis整合 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读