Spring MVC Spring MyBatis 整合 - 快速上手

我个人比较喜欢写注释,在工作中对注释的重要性看的也比较高,所以大部分文字都在注释中,代码外的文字会写的偏少,关键能懂就行

先看一下整合后的工程目录(单工程,多工程以后会采用maven)

Spring MVC Spring MyBatis 整合 - 快速上手

5个package分别对应 action, entity, mapper(也就是DAO,采用动态代理), service, service 实现类

resources 下 相关资源文件:

db.properties: 数据库连接参数

log4j.properties: 日志

applicationContext-dao.xml: spring 和 mybatis 整合的一些配置(sqlSessionFactory,mapper 配置)
applicationContext-service.xml: 业务
applicationContext.xml: spring 核心配置文件(配置一些公用的内容,比如数据源,事务)
springmvc.xml: springmvc 全局配置文件

SqlMapConfig.xml: mybatis 全局配置文件

webapp结构简单就不多说了

下面先贴出maven的pom内容:

 <?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lee</groupId>
<artifactId>ssm</artifactId>
<name>maven-ssm-hello</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.7</java-version>
<org.springframework-version>3.2.3.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties> <dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency> <!-- data source: dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency> <!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency> <!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency> <!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency> <!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency> <!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency> <!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency> <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.34</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.2</version>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin> <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>

相关资源文件:

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> <!-- 定义别名 -->
<typeAliases>
<!-- 批量别名定义
name:指定包名,将包下边的所有pojo定义别名 ,别名为类名(首字母大写或小写都行)
-->
<package name="com.mybatis.bean"/>
</typeAliases> </configuration>

applicationContext-dao.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 配置SqlMapConfig.xml -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
</bean> <!--
使用mapper 批量扫描器扫描mapper接口
不需要id,规则:mapper.xml 与 mapper.java 同名并且在同一个包下
扫描出来的mapper会自动向spring容器中注册,bean的id就是类名(首字母小写)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置会话工厂 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property>
<!--
扫描包的路径
如果有多个mapper的包,那就用半角的 ',' 来隔开
-->
<property name="basePackage" value="com.lee.ssm.dao.mapper"></property>
</bean> </beans>

applicationContext-service.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 用户管理 -->
<!-- <bean id="userService" class="com.lee.ssm.service.impl.UserServiceImpl" /> -->
</beans>

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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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-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"> <!-- 加载配置文件 -->
<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}" />
<!-- 开发阶段数据库最大连接数建议设置小一点够用即可,设置为3 ***发布的时候要开*** -->
<property name="maxActive" value="${jdbc.maxActive}" />
<property name="maxIdle" value="${jdbc.maxIdle}" />
</bean> <!-- 事务管理器
mybatis使用jdbc事务管理
-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean> <!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--
配置传播行为
七种配置 - Spring中Propagation类的事务属性:
REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。
MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。
REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。
NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。
**这个配置将影响数据存储,必须根据情况选择。
-->
<tx:attributes>
<!--
name: 目标方法的范围, 例如: save* 就是以save开头的所有方法名(saveUser, saveStudent...)
isolation: 数据库隔离级别, 一般都是默认default, 有脏读幻读不可重复读等, 设置后会对数据库性能有一定的影响
read-only: true只读事务 false读写事务
propagation: 事务的传播属性, 可以解决事务的嵌套问题
-->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="display*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice> <!-- aop配置 -->
<aop:config>
<!-- aop通知 -->
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.lee.ssm.service.impl.*.*(..))"/>
</aop:config> </beans>

springmvc.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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"> <!-- 组建扫描 -->
<context:component-scan base-package="com.lee.ssm" /> <annotation-driven /> <resources mapping="/resources/**" location="/resources/" /> <!--
视图解析器, 解析jsp, 默认使用jstl, lib中要包含
-->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean> </beans:beans>

db.properties

 jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/order
jdbc.username=root
jdbc.password=root
jdbc.maxActive=3
jdbc.maxIdle=1

HelloController.java

 package com.lee.ssm.action;

 import javax.annotation.Resource;

 import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import com.lee.ssm.bean.User;
import com.lee.ssm.service.IUserService; /**
*
* @Title: HelloController.java
* @Package com.lee.ssm.action
* @Description: TODO
* Copyright: Copyright (c) 2016
* Company:Nathan.Lee.Salvatore
*
* @author leechenxiang
* @date 2016年3月25日 下午10:34:51
* @version V1.0
*/
@Controller
@RequestMapping("/root")
public class HelloController { @Resource
private IUserService userService; /**
*
* @Description: TODO
* @param model
* @return
* @throws Exception
*
* @author leechenxiang
* @date 2016年3月25日 下午10:36:49
*/
@RequestMapping(value = "/hello")
public String home(Model model) throws Exception { User user = userService.findUserById(1);
model.addAttribute("username", user.getName()); return "home";
} }

User.java

 package com.lee.ssm.bean;

 public class User {

     private int id;
private String username;
private int age;
private String sex; public User() {
super();
} public User(String username, int age, String sex) {
super();
this.username = username;
this.age = age;
this.sex = sex;
} public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return username;
}
public void setName(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
} @Override
public String toString() {
return "User [id=" + id + ", name=" + username + ", age=" + age + ", sex="
+ sex + "]";
} }

UserMapper.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.lee.ssm.dao.mapper.UserMapper" > <select id="findUserById" parameterType="int" resultType="com.lee.ssm.bean.User">
SELECT * FROM USER WHERE id = #{id}
</select> <insert id="insertUser" parameterType="com.lee.ssm.bean.User">
insert into user(username,sex) values(#{name},#{sex})
</insert> <delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete> <update id="updateUser" parameterType="com.lee.ssm.bean.User">
update user set username=#{name},sex=#{sex} where id=#{id}
</update> </mapper>

UserMapper.java

 package com.lee.ssm.dao.mapper;

 import com.lee.ssm.bean.User;

 public interface UserMapper {

     public User findUserById(int id) throws Exception;

     public Integer insertUser(User user) throws Exception;

     public void deleteUser(int id) throws Exception;

     public void updateUser(User user) throws Exception;
}

IUserService.java

 package com.lee.ssm.service;

 import com.lee.ssm.bean.User;

 public interface IUserService {

     public User findUserById(int id) throws Exception;

     public void displayUser() throws Exception;

 }

UserServiceImpl.java

 package com.lee.ssm.service.impl;

 import javax.annotation.Resource;

 import org.springframework.stereotype.Service;

 import com.lee.ssm.bean.User;
import com.lee.ssm.dao.mapper.UserMapper;
import com.lee.ssm.service.IUserService; @Service("userService")
public class UserServiceImpl implements IUserService { @Resource
private UserMapper userMapper; @Override
public User findUserById(int id) throws Exception {
return userMapper.findUserById(id);
} @Override
public void displayUser() throws Exception { User u1 = new User("nathan.lee.salvatore", 18, "女");
userMapper.insertUser(u1); userMapper.deleteUser(1001); // int a = 1 / 0; User u2 = new User("lee", 22, "男");
u2.setId(16);
userMapper.updateUser(u2); } }

web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 加载spring 容器, 通配符 加载spring的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml, classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- post乱码处理 -->
<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> <!-- 前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--
contextConfigLocation 指定spring mvc 全局配置文件
如果 contextConfigLocation不指定,默认找配置文件名称:servlet的name+"-servlet.xml"
-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<!-- 容器在应用启动时就加载并初始化这个servlet -->
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> </web-app>

home.jsp

 <?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
user's name is:
<font color="red">${username }</font>
</body>
</html>

启动tomcat,测试地址:http://localhost:8080/ssm/root/hello

具体代码可以参考github: https://github.com/leechenxiang/maven-ssm-hello

上一篇:Redhat Linux内核升级全记录(转)


下一篇:Eclipse中自动提示的方法参数都是arg0,arg1的解决方法