SSM整合入门案例

12 篇文章 0 订阅
11 篇文章 0 订阅

本案例框架版本:
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包

  1. spring(包括spring-mvc)所需jar
  2. MyBatis jar包
  3. mybatis-spring整合jar包
  4. 数据库驱动包
  5. 链接池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>
测试

在这里插入图片描述

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

robona

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值