SpringMVC4 + MyBatis3 + SQL Server 2014整合教程(含增删改查分页)
作者:garfieldzf
前言
说起整合自然离不开ssm,我本身并不太喜欢ORM,尤其是MyBatis,把SQL语句写在xml里,尤其是大SQL,可读性不高,出错也不容易排查。
开发环境
idea2016、SpringMVC4、Mybatis3
项目结构
SSM整合
1、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>com.autohome</groupId> <artifactId>SpringMVC3</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>SpringMVC3</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>sqljdbc4</artifactId> <version>4.0</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> </dependencies> <build> <finalName>SpringMVC3</finalName> </build> </project>
2、web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <!--告知javaEE容器,有那些内容需要添加到上下文里去--> <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> <!--spring 前端控制器--> <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:springmvc-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3、applicationContext.xml无配置内容所以忽略
4、springmvc-servlet.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!--从配置文件加载数据库信息--> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:config/jdbc.properties"/> <property name="fileEncoding" value="UTF-8"/> </bean> <!--配置数据源,这里使用Spring默认--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${sqlserver.driver}"/> <property name="url" value="${sqlserver.url}"/> <property name="username" value="${sqlserver.username}"/> <property name="password" value="${sqlserver.password}"/> </bean> <!--扫描Mapper--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.autohome.mapper"/> </bean> <!--配置sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:springmvc-mybatis.xml"/> <property name="dataSource" ref="dataSource"/> </bean> <!--启用最新的注解器、映射器--> <mvc:annotation-driven/> <!--扫描Controller注解类--> <context:component-scan base-package="com.autohome.controller" /> <!--扫描Service注解类--> <context:component-scan base-package="com.autohome.service"/> <!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
5、springmvc-mybatis.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 alias="User" type="com.autohome.model.User" /> </typeAliases> <mappers> <mapper resource="mapper/UserMapper.xml" /> </mappers> </configuration>
6、dao接口层、mapper(dao接口实现层)、Biz层、 model层忽略不计(id,name,address3个测试字段)。 mapper文件让我踩了坑,后恍然大悟,mapper.xml要放在resources包下。
public interface UserMapper { List<User> listAllUser(); List<User> listPagedUser(@Param("pageIndex") int pageIndex,@Param("pageSize") int pageSize); int count(); int updateUser(User user); int deleteUser(int id); int insertUser(User user); User getUserById(int id); }
<?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.autohome.mapper.UserMapper"> <select id="listAllUser" resultType="User"> select * from t_userinfo </select> <select id="listPagedUser" resultType="User"> select top ${pageSize} * from t_userinfo where id not in (select top (${pageSize} * (${pageIndex} -1)) id from t_userinfo) </select> <select id="count" resultType="int"> select count(*) from t_userinfo </select> <insert id="insertUser" parameterType="User"> insert into t_userinfo VALUES (#{name},#{address}) </insert> <update id="updateUser" parameterType="User"> UPDATE t_userinfo set name=#{name},address=#{address} where id=#{id} </update> <delete id="deleteUser" parameterType="int"> DELETE FROM t_userinfo where id=#{id} </delete> <select id="getUserById" resultType="User" parameterType="int"> select * from t_userinfo where id=#{id} </select> </mapper>
public interface IUserBiz { List<User> listAllUser(); List<User> listPagedUser(@Param("pageIndex") int pageIndex, @Param("pageSize") int pageSize); int count(); int updateUser(User user); int deleteUser(int id); int insertUser(User user); User getUserById(int id); }
package com.autohome.service; import com.autohome.model.User; import com.autohome.mapper.UserMapper; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class UserBizImpl implements IUserBiz { @Autowired private UserMapper userMapper; public List<User> listAllUser() { return userMapper.listAllUser(); } public List<User> listPagedUser(@Param("pageIndex") int pageIndex,@Param("pageSize") int pageSize) { return userMapper.listPagedUser(pageIndex,pageSize); } public int count() { return userMapper.count(); } public int updateUser(User user) { return userMapper.updateUser(user); } public int deleteUser(int id) { return userMapper.deleteUser(id); } public int insertUser(User user) { return userMapper.insertUser(user); } public User getUserById(int id) { return userMapper.getUserById(id); } }
7、Controller。 我新建了一个UserController,在这里调用了增删改查分页的操作
package com.autohome.controller; import com.autohome.service.IUserBiz; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.autohome.model.User; @Controller @RequestMapping("/User") public class UserController { @Autowired private IUserBiz userBiz; @RequestMapping("/index") public ModelAndView index(){ //System.out.println("size:"+userBiz.listAllUser().size()); System.out.println("size:"+userBiz.count()); // // User user =new User(); // user.setName("张三"); // user.setAddress("shanxi"); // // int result = userBiz.insertUser(user); // if(result>0) // { // System.out.println("insert success"); // }else{ // System.out.println("insert err"); // } int result = userBiz.deleteUser(39); if(result>0) { System.out.println("delete success"); }else{ System.out.println("delete err"); } // User user =new User(); // user.setId(35); // user.setName("张三11111"); // user.setAddress("china"); // // int result = userBiz.updateUser(user); // if(result>0) // { // System.out.println("update success"); // }else{ // System.out.println("update err"); // } //System.out.println("size:"+userBiz.listPagedUser(1,10).size()); ModelAndView mav=new ModelAndView("index"); return mav; } }
总结
做这个demo前我看的ssm整合教程全部是基于myeclipse开发的,而且教程把dao接口和dao实现是全部放在src java目录下的,也就是mapper目录包括了mapper接口和mapper.xml。 我做第一个demo时在idea里也是这么做的,demo运行始终不成功,一直提示找不 到mapper.xml里的方法,后来编译的时候我发现target/classes里确实找不到mapper.xml。 不知道用myeclipse整合开发时是否遇到这个问题,后我把mapper.xml文件放到resources目录中,编译后target文件总就能找到mapper.xml。 方法运行也搞定了。写demo写了半个小时,debug这个问题花了2个小时,好在demo跑起来了,也算是有收获的。
好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。