本案例框架版本:
Spring 4.2.4 RELEASE
Spring MVC 4.2.4 RELEASE
MyBatis 3.4.5
数据库案例准备
新建数据库ssm ,在ssm中新建数据表student和grade
##新建grade
CREATE TABLE `NewTable` (
`grade_id` int(4) NOT NULL AUTO_INCREMENT ,
`grade_name` varchar(7) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
PRIMARY KEY (`grade_id`)
)ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
AUTO_INCREMENT=1
ROW_FORMAT=COMPACT;
##插入数据
INSERT INTO `ssm`.`grade` (`grade_id`, `grade_name`) VALUES ('1', '大一');
INSERT INTO `ssm`.`grade` (`grade_id`, `grade_name`) VALUES ('2', '大二');
##新建student
CREATE TABLE `NewTable` (
`student_id` int(4) NOT NULL AUTO_INCREMENT ,
`student_name` varchar(7) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`age` int(3) NULL DEFAULT NULL ,
`grade_id` int(4) NOT NULL ,
PRIMARY KEY (`student_id`),
FOREIGN KEY (`grade_id`) REFERENCES `grade` (`grade_id`) ON DELETE CASCADE ON UPDATE CASCADE,
INDEX `grade_id` (`grade_id`) USING BTREE
)ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
AUTO_INCREMENT=1
ROW_FORMAT=COMPACT;
##插入数据
INSERT INTO `ssm`.`student` (`student_id`, `student_name`, `age`, `grade_id`) VALUES ('1', '张三', '18', '1');
INSERT INTO `ssm`.`student` (`student_id`, `student_name`, `age`, `grade_id`) VALUES ('2', '李四', '18', '1');
INSERT INTO `ssm`.`student` (`student_id`, `student_name`, `age`, `grade_id`) VALUES ('3', '王五', '20', '2');
搭建环境
1)新建java web项目
选中环境以及web.xml的版本:
连点两次Next,勾选自动生成web.xml
2)导入jar包
- spring(包括spring-mvc)所需jar
- MyBatis jar包
- mybatis-spring整合jar包
- 数据库驱动包
- 链接池jar包
3)创建工程结构
整和思路
分层:
表现层:通过controller实现,调用service业务层
业务层:通过spring管理service,调用mapper接口
持久层:使用mapper动态代理实现
mapper,service,handler(controller)都是Java bean
配置:
spring-mvc.xml:自动包扫描,mvc注解视图解析器等mvc配置
applicationContext-dao.xml:数据量连接,mapper扫描等配置
applicationContext-service.xml:配置业务层扫描
applicationContext-trans.xml:配置Spring事务
SqlMapConfig.xml:mybatis核心配置
4)db.properties
#mysql的驱动
driver=com.mysql.jdbc.Driver
#连接地址
url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8
#连接用户名
user=root
#连接密码
password=123456
#初始化数量
initsize=5
#最大数量
maxsize=15
5)log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
6)SqlMapConfig.xml
这个全局配置文件就没什么东西了,因为数据源、mapper都交给Spring去管理了。
<?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>
</configuration>
7)applicationContext-dao.xml
注意:一定记得加载mybatis的全局配置文件
可配置一下数据源、sqlSessionFactory和mapper扫描器, 这样的话,数据源,sqlSessionFactory和mapper在tomcat启动时就被Spring实例化到了容器中。
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 导入资源文件 db.properties-->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置dbcp连接池参数使用Spring表达式来传值 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}"></property>
<property name="username" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="url" value="${url}"></property>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="${initsize}" />
<!-- 连接池的最大值 -->
<property name="maxActive" value="${maxsize}" />
</bean>
<!-- 配置一个bean SqlSessionFactory对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置连接池 -->
<property name="dataSource" ref="dataSource"></property>
<!-- MyBatis的核心文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
</bean>
<!-- 配置包扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置要扫描的包 -->
<property name="basePackage" value="com.oak.ssm.mapper" />
</bean>
</beans>
8)applicationContext-service.xml
指定service层注解扫描
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--指定注解扫描包路径-->
<context:component-scan base-package="com.oak.ssm.service"/>
</beans>
9)applicationContext-trans.xml
Spring 事务管理
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 事务管理器,用的是Spring JDBC的事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.oak.ssm.service.*.*(..))" />
</aop:config>
</beans>
-
propagation=”REQUIRED”:如果当前方法执行的时候,没有事务要开启事务,如果有事务,就在当前事务中执行。也可理解为当前方法被调用的时候没有事务传递进来,就自己开启事务。
-
propagation=”SUPPORTS”:如果当前方法执行的时候,如果有事务,就在当前事务中执行,如果没有事务就不开启事务。也可理解为当前方法被调用的时候没有事务传递进来,自己不开启事务。
10 spring-mvc.xml
配置处理器映射器、处理器适配器和视图解析器
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!--指定注解扫描包路径-->
<context:component-scan base-package="com.oak.ssm.controller"/>
<!-- 开启Spring mvc注解扫描,处理器映射器和适配器均不需要再配置 -->
<mvc:annotation-driven/>
<!--定义视图解析器ViewResolver -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀属性 返回的视图以prefix属性的值作为开头-->
<property name="prefix" value="/WEB-INF/"/>
<!-- 后缀属性 返回的视图以suffix属性的值作为结尾-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
11)web.xml
配置前端控制器和加载Spring 容器
<?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" id="WebApp_ID" version="3.0">
<display-name>ssm_demo01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 初始化Spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 指定springmvc配置文件的路径。如果不指定,默认为:/WEB-INF/${servlet-name}-servlet.xml -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
基于以上环境测试
编写业务层service接口
public interface StudentService {
/**
* @param example
* @return
*/
List<Student> list(StudentExample example);
}
编写业务层实现:
@Service
public class StudentServiceImpl implements StudentService{
@Autowired
private StudentMapper studentMapper;
@Override
public List<Student> list(StudentExample example) {
return studentMapper.selectByExample(example);
}
}
实现Controller
@Controller
@RequestMapping("/stu")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("/list")
public ModelAndView stuList(StudentExample example) throws IOException{
ModelAndView model=new ModelAndView();
model.addObject("stus",studentService.list(example));
System.out.println(studentService.list(example));
model.setViewName("jsp/student_list");
return model;
}
}
编写jsp
<body>
<c:forEach items="${stus }" var="stu">
id:${stu.studentId }
name:${stu.studentName }
age:${stu.age }
<br/>
</c:forEach>
</body>