整合SSM
一、导入jar包
导入spring、springmvc、mybatis、c3p0、ehcache、mysql的jar包。
aopalliance-.jar
asm-4.2.jar
aspectjrt.jar
aspectjtools.jar
aspectjweaver.jar
c3p0-0.9.5.2.jar
c3p0-oracle-thin-extras-0.9.5.2.jar
cglib-3.1.jar
commons-logging-1.2.jar
ehcache-core-2.6.8.jar
jstl.jar
log4j-1.2.17.jar
log4j-api-2.2.jar
log4j-core-2.2.jar
mchange-commons-java-0.2.11.jar
mybatis-3.3.0.jar
mybatis-ehcache-1.0.3.jar
mybatis-spring-1.2.3.jar
mysql-connector-java-5.1.46.jar
org.aspectj.matcher.jar
slf4j-api-1.7.12.jar
slf4j-log4j12-1.7.12.jar
spring-aop-4.2.5.RELEASE.jar
spring-aspects-4.2.5.RELEASE.jar
spring-beans-4.2.5.RELEASE.jar
spring-context-4.2.5.RELEASE.jar
spring-context-support-4.2.5.RELEASE.jar
spring-core-4.2.5.RELEASE.jar
spring-expression-4.2.5.RELEASE.jar
spring-instrument-4.2.5.RELEASE.jar
spring-instrument-tomcat-4.2.5.RELEASE.jar
spring-jdbc-4.2.5.RELEASE.jar
spring-orm-4.2.5.RELEASE.jar
spring-oxm-4.2.5.RELEASE.jar
spring-tx-4.2.5.RELEASE.jar
spring-web-4.2.5.RELEASE.jar
spring-webmvc-4.2.5.RELEASE.jar
standard.jar
二、添加配置文件
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>SSMDemo</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>
<!-- 1. 配置 Spring 的核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置spring的applicationContext.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring.xml</param-value>
</context-param>
<!-- 2. 配置字符编码过滤器,必须在所有的filter最前面 -->
<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>
<!-- 3. 配置可以把 POST 请求转为 DELETE 或 POST 请求 -->
<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>
<!-- 4. 配置 SpringMVC 的DispatcherServlet -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring配置文件
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" 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/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<!-- 1. 配置自动扫描的包 -->
<context:component-scan base-package="com.znsd.ssm">
<!-- 过滤SpringMVC的注解不扫描 -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
<!-- 2. 配置数据源 -->
<context:property-placeholder location="classpath:config/db.properties" />
<!-- C3P0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
</bean>
<!--4、Mybatis配置文件-->
<!-- Spring扫描所有的mapper文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis配置文件 -->
<property name="configLocation" value="classpath:config/mybatis-config.xml" />
<!-- Mappper所在的包路径 -->
<property name="mapperLocations" value="classpath:com/znsd/ssm/mapper/*.xml" />
</bean>
<!-- Spring 扫描DAO包 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- DAO包所在的包路径 -->
<property name="basePackage" value="com.znsd.ssm.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 4. 配置事务管理 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 5. 配置支持注解的事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root
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">
<configuration>
<!-- 通过全局配置文件设置延迟加载-->
<settings>
<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。 -->
<setting name="aggressiveLazyLoading" value="false" />
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"></setting>
</settings>
</configuration>
mybatis-ehcache.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>
<!-- 通过全局配置文件设置延迟加载-->
<settings>
<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。 -->
<setting name="aggressiveLazyLoading" value="false" />
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"></setting>
</settings>
</configuration>
ehcache.xml
<ehcache>
<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
<cache name="sampleCache1" maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />
<cache name="sampleCache2" maxElementsInMemory="1000" eternal="true"
timeToIdleSeconds="0" timeToLiveSeconds="0" overflowToDisk="false" />
<cache name="fiveMinsCache" maxElementsInMemory="10000"
timeToLiveSeconds="300" eternal="false" overflowToDisk="false"
diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000"
diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" statistics="false" clearOnFlush="true" />
</ehcache>
spring-mvc.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"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<!-- 1. 配置自动扫描的包 -->
<context:component-scan base-package="com.znsd.ssm" use-default-filters="false">
<!-- 这两个注解交给SpringMVC管理,其他的交给 IOC 容器 -->
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
<!-- 2. 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:default-servlet-handler />
<mvc:annotation-driven></mvc:annotation-driven>
<!--引入ehcache配置文件-->
<import resource="classpath:config/spring-ehcache.xml"/>
</beans>
log4j.properties
log4j.rootLogger=debug,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
数据表
#班级表
DROP TABLE IF EXISTS `tb_clazz`;
CREATE TABLE `tb_clazz` (
`c_id` int(11) NOT NULL AUTO_INCREMENT,
`c_name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`c_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
#学生表
DROP TABLE IF EXISTS `tb_student`;
CREATE TABLE `tb_student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`pass` varchar(20) DEFAULT NULL,
`sex` varchar(2) DEFAULT NULL,
`address` varchar(100) DEFAULT NULL,
`c_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_cid` (`c_id`),
CONSTRAINT `fk_cid` FOREIGN KEY (`c_id`) REFERENCES `tb_clazz` (`c_id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
实体层
Clazz.java
package com.znsd.ssm.entities;
import java.io.Serializable;
import org.springframework.stereotype.Component;
@Component
public class Clazz implements Serializable{
public Clazz() {
}
public Clazz(Integer clsid, String clsName) {
this.clsid = clsid;
this.clsName = clsName;
}
private Integer clsid;
private String clsName;
public Integer getClsid() {
return clsid;
}
public void setClsid(Integer clsid) {
this.clsid = clsid;
}
public String getClsName() {
return clsName;
}
public void setClsName(String clsName) {
this.clsName = clsName;
}
@Override
public String toString() {
return "Clazz [clsid=" + clsid + ", clsName=" + clsName + "]";
}
}
Student.java
package com.znsd.ssm.entities;
import java.io.Serializable;
import org.springframework.stereotype.Component;
@Component
public class Student implements Serializable{
public Student() {
}
public Student(String name, String pass, String sex, String address) {
this.name = name;
this.pass = pass;
this.sex = sex;
this.address = address;
}
private Integer id;
private String name;
private String pass;
private String sex;
private String address;
private Clazz clazz;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", pass=" + pass + ", sex=" + sex + ", address=" + address
+ "]";
}
}
Dao层
ClazzMapper.java
package com.znsd.ssm.dao;
import java.util.List;
import com.znsd.ssm.entities.Clazz;
public interface ClazzMapper {
public List<Clazz> getClazzList();
public Clazz getClazzOne(Integer clsid);
}
ClazzMapper.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.znsd.ssm.dao.ClazzMapper">
<resultMap type="com.znsd.ssm.entities.Clazz" id="clazzResutMap">
<id column="c_id" property="clsid" />
<result column="c_name" property="clsName"/>
</resultMap>
<select id="getClazzList" resultMap="clazzResutMap">
select * from tb_clazz c;
</select>
<select id="getClazzOne" resultMap="clazzResutMap">
select * from tb_clazz where c_id = #{id}
</select>
</mapper>
StudentMapper.java
package com.znsd.ssm.dao;
import java.util.List;
import com.znsd.ssm.entities.Student;
public interface StudentMapper {
public List<Student> selectStudentAll();
public Student selectStudentOne(Integer id);
public int addStudent(Student student);
public int updateStudent(Student student);
public int deleteStudent(Integer id);
public List<Student> selectStudentByListId(List<Integer> ids);
}
StudentMapper.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.znsd.ssm.dao.StudentMapper">
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<resultMap type="com.znsd.ssm.entities.Student" id="studentResultMap">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="pass" property="pass"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
<!-- 直接在resultMap中强行配置映射属性(不推荐) -->
<result column="c_id" property="clazz.clsid"/>
<result column="c_name" property="clazz.clsName"/>
<!-- 通过association来设置关联关系,通过resultMap来引用clazz映射文件中配置resultMap(推荐) -->
<!-- <association property="clazz" javaType="com.znsd.mybatis.entities.Clazz" -->
<!-- resultMap="com.znsd.mybatis.dao.ClazzMapper.clazzResutMap"> -->
<!-- <id column="c_id" property="clsid" /> -->
<!-- <result column="c_name" property="clsName"/> -->
<!-- </association> -->
<!-- 通过association来设置分布查询,先查询student对象,然后再通过select配置查询另一个表的属性 -->
<!-- <association property="clazz" column="c_id" fetchType="lazy" -->
<!-- select="com.znsd.mybatis.dao.ClazzMapper.getClazzOne"> -->
<!-- </association> -->
</resultMap>
<select id="selectStudentAll" resultMap="studentResultMap">
select * from tb_student s inner join tb_clazz c on s.c_id = c.c_id
</select>
<select id="selectStudentOne" parameterType="int" resultMap="studentResultMap">
select * from tb_student s where id = #{id}
</select>
<select id="selectStudentByClsId" parameterType="int" resultMap="studentResultMap">
select * from tb_student s where c_id = #{c_id}
</select>
<insert id="addStudent" useGeneratedKeys="true" keyProperty="id">
insert into tb_student (name,pass,sex,address)
values(#{name},#{pass},#{sex},#{address})
</insert>
<update id="updateStudent" >
update tb_Student
<!-- 可以根据条件添加set,并且将最后一个,条件去掉 -->
<set>
<if test="name != null and name != ''">
name=#{name},
</if>
<if test="pass != null and pass != ''">
pass=#{pass},
</if>
<if test="sex != null and sex != ''">
sex=#{sex},
</if>
<if test="address != null and address != ''">
address=#{address},
</if>
</set>
where id = #{id}
</update>
<delete id="deleteStudent" parameterType="int">
delete from tb_Student where id = #{id}
</delete>
<select id="selectStudentByListId" resultMap="studentResultMap" >
select * from tb_student where id in
<foreach collection="list" item="item" index="i" open="(" close=")" separator=",">
${item}
</foreach>
</select>
</mapper>
Service层
package com.znsd.ssm.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.znsd.ssm.dao.StudentMapper;
import com.znsd.ssm.entities.Student;
@Service
@Cacheable(value={"fiveMinsCache"})
public class StudentService {
@Autowired
private StudentMapper studentMapper;
public List<Student> getList(){
return studentMapper.selectStudentAll();
}
}
Controllor层
StudentControllor.java
package com.znsd.ssm.controllors;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.znsd.ssm.entities.Student;
import com.znsd.ssm.service.StudentService;
@Controller
public class StudentControllor {
@Autowired
private StudentService studentService;
@RequestMapping("/getlist")
public String getList(){
List<Student> list = studentService.getList();
System.out.println("----------------------------" + list.size());
return "list";
}
}
View层
在views文件夹中添加测试list.jsp页面