框架篇:Spring+SpringMVC+Mybatis整合开发
前言:
前面我已搭建过ssh框架(http://www.cnblogs.com/xrog/p/6359706.html)。
然而mybatis表示不服啊。 Hibernate:“不服便战!”
我们先看下对战双方阵势:
Hiberate VS Mybatis
第一回合:开发速度
刷图难度:Hibernate前期升级需要大量经验,所以你想玩转Hibernate,得多打打小怪,看看攻略什么的.
Mybatis相对简单许多,只要MySQL这件装备强化上去,刷怪轻轻松松
刷图效率:Mybatis需要我们手动写sql语句,回归最原始的方式,所以可以按需求制定查询的字段,
提高效率,由于是自己编写sql语句,所以查询的灵活度也比hibernate高。
Hibernate的查询会将表中的所有字段查询出来,这一点性能消耗比Mybatis大。当然,
Hibernate也可以自己写SQL来指定需要查询的字段,但这样就破坏了Hibernate封装
以及开发的简洁性。
第二回合:数据库移植性
Mybatis由于所有SQL都是依赖数据库书写的,所以扩展性,迁移性比较差。
Hibernate与数据库具体的关联都在XML中,所以HQL对具体是用什么数据库并不是很关心。
第三回合:缓存机制对比
相同点:Hibernate和Mybatis的二级缓存除了采用系统默认的缓存机制外,都可以通过实现你自己的缓存或为
其他第三方缓存方案,创建适配器来完全覆盖缓存行为。
不同点:Hibernate的二级缓存配置在SessionFactory生成的配置文件中进行详细配置,
然后再在具体的表-对象映射中配置是那种缓存。
MyBatis的二级缓存配置都是在每个具体的表-对象映射中进行详细配置,这样针对不同的表可以自定义
不同的缓存机制。并且Mybatis可以在命名空间中共享相同的缓存配置和实例,通过Cache-ref来实现。
两者比较:因为Hibernate对查询对象有着良好的管理机制,用户无需关心SQL。所以在使用二级缓存时如果出现脏数据,
系统会报出错误并提示。而MyBatis在这一方面,使用二级缓存时需要特别小心。如果不能完全确定数据更新
操作的波及范围,避免Cache的盲目使用。否则,脏数据的出现会给系统的正常运行带来很大的隐患。
总结:
Mybatis:小巧、方便、高效、简单、直接、半自动化
Hibernate:强大、方便、高效、复杂、间接、全自动化
好了,没时间解释了,快上车
导包
还是老套路,就不多说了,配置pom.xml:
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>XRom</groupId> <artifactId>ssm</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>ssm Maven Webapp</name> <url>http://maven.apache.org</url> <!--此处统一配置版本信息--> <properties> <!-- spring版本 --> <springVersion>4.3.1.RELEASE</springVersion> <!-- mybatis版本 --> <mybatis.version>3.2.6</mybatis.version> <!--<mysqlVersion>6.0.3</mysqlVersion>--> <mysqlVersion>5.1.38</mysqlVersion> <lombokVersion>1.16.10</lombokVersion> <log4jVersion>1.2.17</log4jVersion> <slf4jVersion>1.7.7</slf4jVersion> <fileuploadVersion>1.3.1</fileuploadVersion> <jstlVersion>1.2</jstlVersion> <!--<taglibVersion>1.1.2</taglibVersion>--> <!--<servletVersion>3.0-alpha-1</servletVersion>--> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springVersion}</version> </dependency> <!-- spring web + spring MVC--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springVersion}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis + spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- DataBase数据库连接 mysql包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysqlVersion}</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- log4j配置, 视情况添加--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4jVersion}</version> </dependency> <!--<dependency>--> <!--<groupId>com.alibaba</groupId>--> <!--<artifactId>fastjson</artifactId>--> <!--<version>1.1.41</version>--> <!--</dependency>--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4jVersion}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4jVersion}</version> </dependency> <!--文件上传包--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${fileuploadVersion}</version> </dependency> <!-- jsp页面使用的jstl支持--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstlVersion}</version> </dependency> <!-- lombok插件导包--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombokVersion}</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>ssm</finalName> <plugins> <!--java8--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!-- mybatis-generator-maven-plugin--> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build> </project>
OK,配置后运行下maven,就会自动向中央仓库下载相应的包啦!另外我这里结尾多配置了两个插件,一个是Java8新特性的,一个是Mybatis Generator的,这两个插件暂时可以不配置
SpringMVC配置
我现在在这里把我配置后的结构拿出来给你们看下,最终的结构就是这样了,当然,部分配置如log4j,generator这些本文章并没用使用到
我们先配置下SpringMVC的配置:resources/META-INF/spring-mvc.xml
ps:这个和上篇博客配置是一样的
<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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- 启动注解驱动的spring MVC功能,注册请求url和注解POJO类方法的映射--> <mvc:annotation-driven /> <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --> <context:component-scan base-package="com.ssm" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="views/" /> <!-- 前缀 --> <property name="suffix" value=".jsp" /> <!-- 后缀 --> </bean> <!--这里是对静态资源的映射--> <mvc:resources mapping="/js/**" location="/resources/js/" /> <mvc:resources mapping="/css/**" location="/resources/css/" /> <mvc:resources mapping="/img/**" location="/resources/img/" /> </beans>
好了,我们现在修改下web.xml这个配置文件,完善下SpringMVC的配置, 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_3_0.xsd" version="3.0"> <!-- 地址为http://localhost:8080/ 显示的默认网页--> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!-- spring MVC config start--> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- 此处指向的的是SpringMVC的配置文件 --> <param-value>classpath:META-INF/spring-mvc.xml</param-value> </init-param> <!--配置容器在启动的时候就加载这个servlet并实例化--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- spring MVC config end--> </web-app>
OK,SpringMVC配置完成,现在我们进行一下测试吧
在controller层新建一个MainController,内容如下
package com.ssm.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Created by XRog * On 2/1/2017.12:36 AM */ @Controller public class MainController { @RequestMapping(value = "test", method = RequestMethod.GET) public String test(){ // 实际返回的是views/test.jsp ,spring-mvc.xml中配置过前后缀 return "test"; } }
test.jsp网页如下:
<html> <body> <center> <h2 style="color: #ff261a;">this is my test page!</h2> </center> </body> </html>
重启Tomcat服务器, 然后浏览器访问http://localhost/test如下图所示:
PS: Tomcat默认端口是8080,我更改了端口号,如若你们未更改,正确的访问地址是localhost:8080/test
OK,成功访问。
SpringMVC+Spring整合
这个就十分简单了, 配置spring-mybatis.xml这个Spring的配置文件如下(后面的mybatis配置我也将写在这里):
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.ssm"> <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
完善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_3_0.xsd" version="3.0"> <!-- 地址为http://localhost:8080/ 显示的默认网页--> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!--加载Spring的配置文件到上下文中去--> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:META-INF/spring-mybatis.xml </param-value> </context-param> <!-- spring MVC config start--> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- 此处指向的的是SpringMVC的配置文件 --> <param-value>classpath:META-INF/spring-mvc.xml</param-value> </init-param> <!--配置容器在启动的时候就加载这个servlet并实例化--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- spring MVC config end--> <!-- Spring监听器 --> <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> </web-app>
web.xml配置文件中更改了三处:引入Spring-mybaits配置文件 Spring的监听器 以及 字符集过滤
OK,Spring+SpringMVC配置完成,下面我们开始测试:
在service写一个TestServiceImpl实现TestService接口并实现其test()方法, 代码如下:
package com.ssm.service.impl; import com.ssm.service.TestService; import org.springframework.stereotype.Service; /** * Created by XRog * On 2/1/2017.12:58 AM */ @Service public class TestServiceImpl implements TestService { public String test() { return "test"; } }
PS:这里注意写@Service注解
MainController控制器更改如下:
package com.ssm.controller; import com.ssm.service.TestService; 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.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by XRog * On 2/1/2017.12:36 AM */ @Controller public class MainController { @Autowired private TestService testService; @RequestMapping(value = "test", method = RequestMethod.GET) public String test(){ // 实际返回的是views/test.jsp ,spring-mvc.xml中配置过前后缀 return "test"; } @RequestMapping(value = "springtest", method = RequestMethod.GET) public String springTest(){ return testService.test(); } }
控制器这里我们运用了Spring的依赖注入自动装配。
在浏览器中输入地址http://localhost/springtest调用springtest方法
yes,成功返回,说明我们之前的配置没问题
Spring+SpringMVC+Mybatis整合
好了,现在就缺Mybatis这个框架了。。 我先给大家看些我搭建好之后的结构图吧
我们先来编写jdbc.properties这个配置文件,里面存放的是mybatis的一些配置
#这个是Mybatis Generator逆向工程要用到的,现在可以不配置
jdbc.driverLocation=C:\\Users\\XRog\\.m2\\repository\\mysql\\mysql-connector-java\\5.1.38\\mysql-connector-java-5.1.38.jar
#数据源
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://zxr1998.com.cn:3306/ssm
jdbc.username=???
jdbc.password=???
#初始化连接池连接数
initialSize=0
#连接池最大连接数
maxActive=20
#连接池最大空闲
maxIdle=20
#连接池最小空闲
minIdle=1
#最大等待时间
maxWait=60000
这里连接数据库的参数由于我是连接我网上的数据库,因此我数据库地址和密码打了“???”,你们连接时改成自己本地的就OK了
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.ssm"> <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 加载配置文件 --> <context:property-placeholder location="classpath:/jdbc.properties" /> <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="initialSize" value="${initialSize}" /> <!--初始化连接池连接数--> <property name="maxActive" value="${maxActive}" /> <!--连接池最大连接数--> <property name="maxIdle" value="${maxIdle}" /> <!--连接池最大空闲--> <property name="minIdle" value="${minIdle}" /> <!--连接池最小空闲--> <property name="maxWait" value="${maxWait}" /> <!--连接最大等待时间--> </bean> <bean id="sqlSessionFaction" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:/mapping/*.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ssm.mapping" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFaction" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
OK,到了这里,配置结束。下面进入测试阶段
实体类(domain):
package com.ssm.domain; public class Person { private Long id; private String username; private String password; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } }
mapping(我这里使用generator生成的,粘贴的时候我去掉了很多注释,莫介意):
package com.ssm.mapping; import com.ssm.domain.Person; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.ResultMap; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectKey; import org.apache.ibatis.annotations.Update; public interface PersonMapper { int deleteByPrimaryKey(Long id); int insert(Person record); int insertSelective(Person record); Person selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(Person record); int updateByPrimaryKey(Person record); }
<?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.ssm.mapping.PersonMapper"> <resultMap id="BaseResultMap" type="com.ssm.domain.Person"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator, do not modify. --> <id column="id" jdbcType="BIGINT" property="id" /> <result column="username" jdbcType="VARCHAR" property="username" /> <result column="password" jdbcType="VARCHAR" property="password" /> </resultMap> <sql id="Base_Column_List"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator, do not modify. --> id, username, password </sql> <insert id="insertSelective" parameterType="com.ssm.domain.Person"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator, do not modify. --> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long"> SELECT LAST_INSERT_ID() </selectKey> insert into person <trim prefix="(" suffix=")" suffixOverrides=","> <if test="username != null"> username, </if> <if test="password != null"> password, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="username != null"> #{username,jdbcType=VARCHAR}, </if> <if test="password != null"> #{password,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.ssm.domain.Person"> <!-- WARNING - @mbggenerated This element is automatically generated by MyBatis Generator, do not modify. --> update person <set> <if test="username != null"> username = #{username,jdbcType=VARCHAR}, </if> <if test="password != null"> password = #{password,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=BIGINT} </update> </mapper>
服务层(service):
package com.ssm.service; import com.ssm.domain.Person; /** * Created by XRog * on 5/27/2017. */ public interface PersonService { int insert(Person person); }
package com.ssm.service.impl; import com.ssm.domain.Person; import com.ssm.mapping.PersonMapper; import com.ssm.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created by XRog * on 5/27/2017. */ @Service public class PersonServiceImpl implements PersonService { @Autowired private PersonMapper personMapper; @Override public int insert(Person person) { return personMapper.insertSelective(person); } }
控制层(controller):
package com.ssm.controller; import com.ssm.domain.Person; import com.ssm.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; /** * Created by XRog * on 5/24/2017. */ @Controller @RequestMapping("/test") public class TestController { @Autowired private PersonService personService; @RequestMapping(value = "mybatis") public @ResponseBody String mybatis(){ Person person = new Person(); person.setUsername("test2"); person.setPassword("123"); personService.insert(person); return "success"; } }
OK,编写完毕,我们重启下服务器然后测试:输入地址 localhost/test/mybatis ,如果不出意外的话将返回success,这说明访问成功
另外,这个ssm项目我已上传到码云,公开了共享,下面是地址.这篇博客很多地方(spring+springmvc )都是借用的上篇博客的,请以下面共享的项目地址为准
https: https://git.oschina.net/zxr_a/ssm.git
ssh: git@git.oschina.net:zxr_a/ssm.git
好了,到这里就结束了,祝大家别出BUG。