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。
项目结构
maven配置文件pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.neu</groupId> <artifactId>spring-over</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>spring-over Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <!--spring相关--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.7</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.5.RELEASE</version> </dependency> <!--servlet和jsp--> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> </dependency> <!--mybatis相关--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>sprig-over</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
webapp配置文件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"> <!--spring监听器--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--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-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--乱码过滤器--> <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>
spring配置文件applicationContext.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--组件扫描 扫描service和mapper--> <context:component-scan base-package="com.neu"> <!--排除controller的扫描--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--加载properties文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--配置数据源信息--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--配饰sessionFactory--> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--mybatis核心文件--> <property name="configLocation" value="classpath:sqlMapConfig-spring.xml"/> </bean> <!--扫描mapper所在的包 未mapper创建实现类--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.neu.mapper"/> </bean> <!--声明式事务控制--> <!--平台事务控制器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--配置事务增强--> <tx:advice id="txAdvice"> <tx:attributes> <tx:method name="*"/> </tx:attributes> </tx:advice> <!--事务aop织入--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.neu.service.impl.*.*(..))"/> </aop:config> </beans>
spring-mvc配置文件spring-mvc.xml
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--组件扫描--> <context:component-scan base-package="com.neu.controller"/> <!--配置mvc注解驱动--> <mvc:annotation-driven/> <!--内部资源视图解析器--> <bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--开放静态资源访问权限--> <mvc:default-servlet-handler/> </beans>
mybatis映射文件AccountMapper.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="com.neu.mapper.AccountMapper"> <insert id="save" parameterType="account"> insert into account(id,name,money) values(#{id},#{name},#{money}) </insert> <select id="findAll" resultType="account"> select * from account </select> </mapper>
mybatis配置文件(两种整合方法)
1.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> <!--加载properties文件--> <properties resource="jdbc.properties"/> <typeAliases> <!--<typeAlias type="com.neu.domain.Account" alias="account"/>--> <package name="com.neu.domain"/> </typeAliases> <!--环境--> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!--加载映射--> <mappers> <mapper resource="com/neu/mapper/AccountMapper.xml"/> </mappers> </configuration>
引入方法
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
<?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.neu.domain.Account" alias="account"/>--> <package name="com.neu.domain"/> </typeAliases> <!--加载映射--> <mappers> <mapper resource="com/neu/mapper/AccountMapper.xml"/> </mappers> </configuration>
spring配置注入
<!--加载properties文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--配置数据源信息--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--配饰sessionFactory--> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--mybatis核心文件--> <property name="configLocation" value="classpath:sqlMapConfig-spring.xml"/> </bean> <!--扫描mapper所在的包 未mapper创建实现类--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.neu.mapper"/> </bean> <!--声明式事务控制--> <!--平台事务控制器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--配置事务增强--> <tx:advice id="txAdvice"> <tx:attributes> <tx:method name="*"/> </tx:attributes> </tx:advice> <!--事务aop织入--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.neu.service.impl.*.*(..))"/> </aop:config>
注入代码
@Autowired private AccountMapper accountMapper; @Override public 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 <http://www.gnu.org/licenses/lgpl-2.1.html>. # ### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.err log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.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
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>添加账户信息表单</h1> <form name="accountForm" action="${pageContext.request.contextPath}/account/save" method="post"> 账户名称:<input type="text" name="name"><br> 账户金额:<input type="text" name="money"><br> <input type="submit" name="保存"><br> </form> </body> </html>
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 { @Autowired private AccountService accountService; @RequestMapping(value = "/save",produces = "text/html;charset=UTF-8") @ResponseBody public String save(Account account){ accountService.save(account); System.out.println(account); return "保存成功"; } @RequestMapping("/findAll") public ModelAndView findAll(){ List<Account> 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 { @Autowired private AccountMapper accountMapper; @Override 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(); // } accountMapper.save(account); } @Override public List<Account> 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<Account> 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<Account> findAll(); }
到此这篇关于Spring+SpringMVC+MyBatis整合实战(SSM框架)的文章就介绍到这了,更多相关Spring SpringMVC MyBatis整合 内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!