1、整合前需要注意的问题
尖叫提示:框架版本是否兼容
1) 查看不同MyBatis版本整合Spring时使用的适配包http://www.mybatis.org/spring/
2)下载整合适配包https://github.com/mybatis/spring/releases
3)官方整合示例,jpetstorehttps://github.com/mybatis/jpetstore-6
2、SSM整合思想
1)导入整合需要的jar包
(1)Spring的jar包
(2)SpringMVC的jar包
(3)MyBatis的jar包
(4)整合的适配包
(5)数据库驱动包、日志包、连接池等
2)MyBatis环境的搭建
(1)MyBatis的全局配置文件
(2)编写javaBean,Mapper接口,sql映射文件
3)Spring SpringMVC环境的搭建
(1)web.xml中配置SpringIOC容器启动的监听器、SpringMVC的核心控制器、REST过滤器
(2)编写Spring的配置文件: applicationContext.xml
(3)编写SpringMVC的配置文件: springmvc.xml
4)Spring整合MyBatis
(1)配置创建SqlSession对象的SqlSessionFactoryBean
(2)配置扫描所有的Mapper接口,批量生成代理实现类,交给Spring管理的,能够完成自动注入.
5)编码测试
完成员工的增删改查.
3、SSM 框架整合实操
1)创建web 工程
(1) File -> New -> Other
(2)Dynamic Web Project -> Next
(3)Project name -> Finish
2)导入jar包
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
commons-logging-1.1.3.jar
(2)Spring MVC jar 包
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
(3)MyBatis jar包
mybatis-3.4.1.jar
(4)JSTL jar 包
taglibs-standard-impl-1.2.1.jar
taglibs-standard-spec-1.2.1.jar
(5)整合的适配包
mybatis-spring-1.3.0.jar
(6)驱动、日志、连接池包
c3p0-0.9.1.2.jar
log4j.jar
mysql-connector-java-5.1.37-bin.jar
(7)反向工程jar包
mybatis-generator-core-1.3.2.jar
(8)log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
(9)分页jar包
pagehelper-5.0.0-rc.jar
jsqlparser-0.9.5.jar
3)MyBatis 环境搭建
思想
MyBatis的全局配置文件
编写javaBean,Mapper接口,sql映射文件
方式
使用逆向工程方式实现
(1)添加逆向工程jar包
mybatis-generator-core-1.3.2.jar
(2)添加mbg.xml 配置文件
mbg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- targetRuntime: 指定生成的逆向工程的版本
MyBatis3: 生成带条件的增删改查.
MyBatis3Simple: 生成基本的增删改查.
-->
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 数据库的连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root"
password="root">
</jdbcConnection>
<!-- 指定javabean的生成策略
targetPackage: 指定包
targetProject: 指定工程
-->
<javaModelGenerator targetPackage="com.alex.ssm.entity" targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- sql映射的生成策略 -->
<sqlMapGenerator targetPackage="com.alex.ssm.mapper" targetProject=".\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- mapper接口的生成策略 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.alex.ssm.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 指定逆向分析的表 -->
<table tableName="tbl_dept" domainObjectName="Department"></table>
<table tableName="tbl_employee" domainObjectName="Employee"></table>
</context>
</generatorConfiguration>
(3)创建包文件
com.alex.ssm.entity
com.alex.ssm.mapper
com.alex.ssm.test
(4)创建逆向工程方法
MyBatisTestMBG.java
package com.alex.mybatis.test;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
public class MyBatisTestMBG {
@Test
public void createMBG() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}
(5)创建db.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true
jdbc.username=root
jdbc.password=root
(6)mybatis-config.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">
<!-- MyBatis的全局配置文件 -->
<configuration>
<!-- properties:
引入外部化的配置文件
resource: 加载类路径下的资源文件
url: 加载网络路径或者是磁盘路径下的资源文件
-->
<properties resource="db.properties" ></properties>
<!-- settings:
包含很多重要的设置项,可以改变MyBatis框架的运行行为
setting:具体的一个设置项
name: 设置项的名称
value:设置项的取值
-->
<settings>
<!-- 映射下划线到驼峰命名 last_name ==> lastName -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 指定加载的属性是按需加载. -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
<!-- typeAliases
别名处理,给java类型取别名(简短)
typeAlias:给单个的java类型取别名
type:指定java类型(全类名)
alias:指定别名。默认的别名是类名的首字母小写. 别名不区分大小写.
package:批量取别名,给指定的包下的所有的类取默认的别名
name:指定包名
-->
<typeAliases>
<!-- <typeAlias type="com.alex.ssm.entity.Employee" alias="employee"/> -->
<package name="com.alex.ssm.entity"/>
</typeAliases>
<!-- environments: 环境们。 支持配置多个环境. 通过default来指定具体使用的环境.
environment: 具体的一个环境配置,必须包含transactionManager,dataSource。
id: 当前环境的唯一标识.
transactionManager: 事务管理器.
JDBC: JdbcTransactionFactory
将来事务管理会交给Spring的声明式事务.@Trancation
dataSource:数据源.
POOLED: PooledDataSourceFactory
将来数据源交给Spring管理,使用c3p0或者dbcp等
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
<environment id="test">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!--
mappers:引入sql映射文件
mapper:引入单个的sql映射文件
package: 批量引入sql映射文件
要求: sql映射文件的名字与Mapper接口的名字一致.并且在同一目录下.
-->
<mappers>
<!-- <mapper resource="EmployeeMapper.xml" /> -->
<package name="com.alex.ssm.mapper"/>
</mappers>
</configuration>
(7)mybatis.sql
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50515
Source Host : localhost:3306
Source Database : mybatis
Target Server Type : MYSQL
Target Server Version : 50515
File Encoding : 65001
Date: 2019-10-16 14:38:06
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tbl_dept
-- ----------------------------
DROP TABLE IF EXISTS `tbl_dept`;
CREATE TABLE `tbl_dept` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`department_name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tbl_dept
-- ----------------------------
INSERT INTO `tbl_dept` VALUES ('1', '开发部');
INSERT INTO `tbl_dept` VALUES ('2', '测试部');
INSERT INTO `tbl_dept` VALUES ('3', '财务部');
INSERT INTO `tbl_dept` VALUES ('4', '人事部');
-- ----------------------------
-- Table structure for tbl_employee
-- ----------------------------
DROP TABLE IF EXISTS `tbl_employee`;
CREATE TABLE `tbl_employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`d_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_emp_dept` (`d_id`),
CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tbl_employee
-- ----------------------------
INSERT INTO `tbl_employee` VALUES ('1001', 'Tom', 'Tom@aliyun.com', '1', '1');
INSERT INTO `tbl_employee` VALUES ('1002', 'Rose', 'rose@aliyun.com', '0', '2');
INSERT INTO `tbl_employee` VALUES ('1003', 'Alex', 'alex@qq.com', '1', '3');
INSERT INTO `tbl_employee` VALUES ('1004', 'Thone', 'Thone@aliyun.com', '0', '4');
INSERT INTO `tbl_employee` VALUES ('1005', 'Jerry', 'jerry@aliyun.com', '1', '2');
(8)创建Mybatis测试方法
package com.alex.mybatis.test;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import com.alex.ssm.entity.Employee;
import com.alex.ssm.entity.EmployeeExample;
import com.alex.ssm.entity.EmployeeExample.Criteria;
import com.alex.ssm.mapper.EmployeeMapper;
public class MyBatisTestMBG {
public SqlSessionFactory getSqlSessionFactory() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
System.out.println(sqlSessionFactory);
return sqlSessionFactory;
}
// 根据id查询
@Test
public void testMBG01() throws Exception {
SqlSessionFactory ssf = getSqlSessionFactory();
SqlSession session = ssf.openSession();
try {
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
Employee employee = mapper.selectByPrimaryKey(1001);
System.out.println(employee);
} finally {
session.close();
}
}
// 没有条件的情况,查询全部信息
@Test
public void testMBG02() throws Exception {
SqlSessionFactory ssf = getSqlSessionFactory();
SqlSession session = ssf.openSession();
try {
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
List<Employee> emps = mapper.selectByExample(null);
for (Employee employee : emps) {
System.out.println(employee);
}
} finally {
session.close();
}
}
// 按照条件查询
@Test
public void testMBG03() throws Exception {
SqlSessionFactory ssf = getSqlSessionFactory();
SqlSession session = ssf.openSession();
try {
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
// 查询员工名字中带有e字母 和员工性别是2的 或者email中带有y字母的
EmployeeExample example = new EmployeeExample();
Criteria criteria = example.createCriteria();
criteria.andLastNameLike("%e%");
criteria.andGenderEqualTo("0");
// or的条件需要重新使用一个Criteria对象
Criteria criteria2 = example.createCriteria();
criteria2.andEmailLike("%y%");
// 对于封装or条件的criteria,需要or到example
example.or(criteria2);
List<Employee> emps = mapper.selectByExample(example);
for (Employee employee : emps) {
System.out.println(employee);
}
} finally {
session.close();
}
}
}
4)Spring SpringMVC 环境的搭建
(1)思想
web.xml中配置
SpringIOC容器启动的监听器
SpringMVC的核心控制器
REST过滤器
UTF-8编码
编写Spring的配置文件: applicationContext.xml
编写SpringMVC的配置文件: springmvc.xml
(2)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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ssm</display-name>
<!-- 实例化SpringIOC容器的监听器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置utf-8编码 -->
<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>
<!-- REST 过滤器 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Springmvc的核心控制器 -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
(3)spring-context.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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.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-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.alex.ssm">
<!-- Springmvc管理的,Spring就不管理 -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 读取外部文件 -->
<context:property-placeholder location="classpath:/db.properties" />
<!-- C3P0 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="driverClass" value="${jdbc.driver}" />
<property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
<property name="minPoolSize" value="${jdbc.minPoolSize}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
<property name="maxStatements" value="${jdbc.maxStatements}" />
<property name="maxStatementsPerConnection" value="${jdbc.maxStatementsPerConnection}" />
</bean>
<!-- 事务切面 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 开启基于注解的声明式事务 transaction-manager="transactionManager" 默认值,可以省略. -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
(4)springmvc-context.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.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-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 注解扫描 -->
<context:component-scan base-package="com.alex.ssm" use-default-filters="false">
<!-- 只扫描SpringMVC相关的组件 -->
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
</beans>
(5)db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true
jdbc.username=root
jdbc.password=root
jdbc.initialPoolSize=30
jdbc.minPoolSize=10
jdbc.maxPoolSize=100
jdbc.acquireIncrement=5
jdbc.maxStatements=1000
jdbc.maxStatementsPerConnection=10
5)Spring整合MyBatis
配置创建SqlSession对象的SqlSessionFactoryBean
配置扫描所有的Mapper接口,批量生成代理实现类,交给Spring管理的,能够完成自动注入.
(1)spring-context.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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.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-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.alex.ssm">
<!-- Springmvc管理的,Spring就不管理 -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 读取外部文件 -->
<context:property-placeholder location="classpath:/db.properties" />
<!-- C3P0 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="driverClass" value="${jdbc.driver}" />
<property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
<property name="minPoolSize" value="${jdbc.minPoolSize}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
<property name="maxStatements" value="${jdbc.maxStatements}" />
<property name="maxStatementsPerConnection" value="${jdbc.maxStatementsPerConnection}" />
</bean>
<!-- 事务切面 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 开启基于注解的声明式事务 transaction-manager="transactionManager" 默认值,可以省略. -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 整合 MyBatis MyBatis的配置都可以在Spring里面配置,但是尽量把MyBatis独有的还是放在MyBatis配置文件里-->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource" ></property>
<!-- 指定MyBatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 指定sql映射文件 -->
<property name="mapperLocations" value="classpath:com/alex/ssm/mapper/*.xml"></property>
</bean>
<!-- 扫描所有mapper接口,批量生成代理实现类,交给Spring容器来管理 -->
<!-- 这是老版本的配置方式,没办法指定ID,ID默认是类的首字母小写 -->
<!--
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.alex.ssm.mapper"></property>
</bean>
-->
<!-- 扫描所有mapper接口,批量生成代理实现类,交给Spring容器来管理 -->
<!-- 新方式 , 两种方式,使用哪一种都可以-->
<mybatis-spring:scan base-package="com.alex.ssm.mapper"/>
</beans>
(2)mybatis-config.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">
<!-- MyBatis的全局配置文件 -->
<configuration>
<settings>
<!-- 映射下划线到驼峰命名 last_name ==> lastName -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 指定加载的属性是按需加载. -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
<package name="com.alex.ssm.entity"/>
</typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
</configuration>
尖叫提示:把交给Spring 管理的从MyBatis配置文件中删掉
6)编码测试
完成员工的增删改查.(1)EmployeeController.java
package com.alex.ssm.controller;
import java.util.List;
import java.util.Map;
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 com.alex.ssm.entity.Employee;
import com.alex.ssm.service.EmployeeService;
@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeService ;
@RequestMapping(value="/emps",method=RequestMethod.GET)
public String listEmps(Map<String,Object> map) {
List<Employee> emps = employeeService.getAllEmps();
map.put("emps",emps);
return "list";
}
}
(2)EmployeeService.java
package com.alex.ssm.service;
import java.util.List;
import com.alex.ssm.entity.Employee;
public interface EmployeeService {
public List<Employee> getAllEmps();
}
(3)EmployeeServiceImpl.Java
package com.alex.ssm.serviceimpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alex.ssm.entity.Employee;
import com.alex.ssm.mapper.EmployeeMapper;
import com.alex.ssm.service.EmployeeService;
@Service
public class EmployeeServiceImpl implements EmployeeService{
@Autowired
private EmployeeMapper employeeMapper ;
@Override
public List<Employee> getAllEmps() {
List<Employee> example = employeeMapper.selectByExample(null);
return example;
}
}
(4)index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/emps">List ALL Emps</a>
</body>
</html>
(5)list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- 导入JSTL标签库 -->
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center" >员工信息列表</h1>
<table border="1px" width="70%" cellspacing="0px" align="center">
<tr>
<th>ID</th>
<th>LastName</th>
<th>Email</th>
<th>Gender</th>
<!-- <th>DeptName</th> -->
<th>Operation</th>
</tr>
<!-- items:指定要迭代的集合 var:代表当前迭代出的对象-->
<c:forEach items="${requestScope.emps }" var="emp">
<tr align="center">
<td>${emp.id }</td>
<td>${emp.lastName }</td>
<td>${emp.email }</td>
<td>${emp.gender==0?'女':'男' }</td>
<%-- <td>${emp.dept.departmentName}</td> --%>
<td>
<a href="#">Edit</a>
<a href="#">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>