SSM简单整合
1.环境
JDK1.8 Eclipse Maven构建工具
2.依赖包配置(pom.xml)
<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/xsd/maven-4.0.0.xsd" >
<modelVersion > 4.0.0</modelVersion >
<groupId > com.lyx</groupId >
<artifactId > ssm_hrs</artifactId >
<version > 1.0</version >
<dependencies >
<dependency >
<groupId > junit</groupId >
<artifactId > junit</artifactId >
<version > 4.12</version >
<scope > test</scope >
</dependency >
<dependency >
<groupId > javax.servlet</groupId >
<artifactId > javax.servlet-api</artifactId >
<version > 3.1.0</version >
<scope > provided</scope >
</dependency >
<dependency >
<groupId > javax.servlet.jsp</groupId >
<artifactId > javax.servlet.jsp-api</artifactId >
<version > 2.3.1</version >
<scope > provided</scope >
</dependency >
<dependency >
<groupId > javax.servlet</groupId >
<artifactId > jstl</artifactId >
<version > 1.2</version >
</dependency >
<dependency >
<groupId > org.mybatis</groupId >
<artifactId > mybatis</artifactId >
<version > 3.4.5</version >
</dependency >
<dependency >
<groupId > org.mybatis</groupId >
<artifactId > mybatis-spring</artifactId >
<version > 1.3.1</version >
</dependency >
<dependency >
<groupId > mysql</groupId >
<artifactId > mysql-connector-java</artifactId >
<version > 5.1.40</version >
</dependency >
<dependency >
<groupId > org.apache.commons</groupId >
<artifactId > commons-dbcp2</artifactId >
<version > 2.1.1</version >
</dependency >
<dependency >
<groupId > commons-codec</groupId >
<artifactId > commons-codec</artifactId >
<version > 1.10</version >
</dependency >
<dependency >
<groupId > org.springframework</groupId >
<artifactId > spring-webmvc</artifactId >
<version > 4.3.10.RELEASE</version >
</dependency >
<dependency >
<groupId > org.springframework</groupId >
<artifactId > spring-orm</artifactId >
<version > 4.3.10.RELEASE</version >
</dependency >
<dependency >
<groupId > org.springframework</groupId >
<artifactId > spring-test</artifactId >
<version > 4.3.10.RELEASE</version >
<scope > test</scope >
</dependency >
<dependency >
<groupId > org.aspectj</groupId >
<artifactId > aspectjrt</artifactId >
<version > 1.8.10</version >
</dependency >
<dependency >
<groupId > org.aspectj</groupId >
<artifactId > aspectjweaver</artifactId >
<version > 1.8.10</version >
</dependency >
<dependency >
<groupId > com.fasterxml.jackson.core</groupId >
<artifactId > jackson-databind</artifactId >
<version > 2.9.0</version >
</dependency >
<dependency >
<groupId > org.freemarker</groupId >
<artifactId > freemarker</artifactId >
<version > 2.3.23</version >
</dependency >
<dependency >
<groupId > org.springframework</groupId >
<artifactId > spring-context-support</artifactId >
<version > 4.3.10.RELEASE</version >
</dependency >
<dependency >
<groupId > com.fasterxml.jackson.core</groupId >
<artifactId > jackson-databind</artifactId >
<version > 2.9.0</version >
</dependency >
</dependencies >
<build >
<resources >
<resource >
<directory > src/main/java</directory >
<includes >
<include > **/*.xml</include >
</includes >
</resource >
</resources >
<plugins >
<plugin >
<groupId > org.apache.maven.plugins</groupId >
<artifactId > maven-war-plugin</artifactId >
<version > 3.2.0</version >
<configuration >
<failOnMissingWebXml > false</failOnMissingWebXml >
</configuration >
</plugin >
<plugin >
<groupId > org.apache.tomcat.maven</groupId >
<artifactId > tomcat7-maven-plugin</artifactId >
<version > 2.2</version >
</plugin >
<plugin >
<groupId > org.apache.maven.plugins</groupId >
<artifactId > maven-compiler-plugin</artifactId >
<configuration >
<source > 1.8</source >
<target > 1.8</target >
</configuration >
</plugin >
</plugins >
</build >
<packaging > war</packaging >
</project >
3.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" >
<servlet >
<servlet-name > frontController</servlet-name >
<servlet-class > org.springframework.web.servlet.DispatcherServlet</servlet-class >
<init-param >
<param-name > contextConfigLocation</param-name >
<param-value > /WEB-INF/spring-config/mvc.xml</param-value >
</init-param >
<load-on-startup > 1</load-on-startup >
<multipart-config />
</servlet >
<servlet-mapping >
<servlet-name > frontController</servlet-name >
<url-pattern > /</url-pattern >
</servlet-mapping >
<context-param >
<param-name > contextConfigLocation</param-name >
<param-value > /WEB-INF/spring-config/spring.xml</param-value >
</context-param >
<listener >
<listener-class > org.springframework.web.context.ContextLoaderListener</listener-class >
</listener >
<filter >
<filter-name > encodingFilter</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 > encodingFilter</filter-name >
<url-pattern > /*</url-pattern >
</filter-mapping >
<display-name > 1011house</display-name >
<welcome-file-list >
<welcome-file > index.html</welcome-file >
<welcome-file > index.jsp</welcome-file >
</welcome-file-list >
</web-app >
4.SpringMVC的配置文件(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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd" >
<context:component-scan base-package ="com.lyx.hrs.controller" />
<mvc:annotation-driven conversion-service ="conversionService" >
<mvc:message-converters >
<bean class ="org.springframework.http.converter.BufferedImageHttpMessageConverter" />
<bean class ="org.springframework.http.converter.StringHttpMessageConverter" />
<bean class ="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</mvc:message-converters >
</mvc:annotation-driven >
<bean id ="conversionService"
class ="org.springframework.format.support.FormattingConversionServiceFactoryBean" >
<property name ="converters" >
<set >
<bean class ="com.lyx.hrs.converter.DateConverter" />
</set >
</property >
</bean >
<mvc:default-servlet-handler />
<bean class ="org.springframework.web.multipart.support.StandardServletMultipartResolver" />
<property name ="order" value ="10" />
</bean > -->
<bean class ="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer" >
<property name ="templateLoaderPath" value ="/WEB-INF/ftl/" />
<property name ="defaultEncoding" value ="utf-8" />
<property name ="freemarkerSettings" >
<props >
<prop key ="classic_compatible" > true</prop >
</props >
</property >
</bean >
<bean class ="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver" >
<property name ="contentType" value ="text/html; charset=utf-8" />
<property name ="cache" value ="true" />
<property name ="prefix" value ="" />
<property name ="suffix" value =".ftl" />
<property name ="order" value ="4" />
</bean >
</beans >
5.Spring的配置文件(spring.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: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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd" >
<context:component-scan base-package ="com.lyx.hrs" >
<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 >
<context:annotation-config />
<bean id ="dataSource" class ="org.apache.commons.dbcp2.BasicDataSource"
destroy-method ="close" >
<property name ="driverClassName" value ="com.mysql.jdbc.Driver" > </property >
<property name ="url" value ="jdbc:mysql://localhost:3306/hrs" > </property >
<property name ="username" value ="root" > </property >
<property name ="password" value ="951112" > </property >
<property name ="initialSize" value ="10" > </property >
<property name ="maxTotal" value ="100" > </property >
<property name ="maxWaitMillis" value ="5000" > </property >
</bean >
<bean id ="sqlSessionFactory" class ="org.mybatis.spring.SqlSessionFactoryBean" >
<property name ="dataSource" ref ="dataSource" />
<property name ="configLocation" value ="classpath:mybatis-config.xml" />
</bean >
<bean class ="org.mybatis.spring.mapper.MapperScannerConfigurer" >
<property name ="basePackage" value ="com.lyx.hrs.mapper" />
<property name ="sqlSessionFactoryBeanName" ref ="sqlSessionFactory" />
</bean >
<bean id ="transactionManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name ="dataSource" ref ="dataSource" > </property >
</bean >
<tx:annotation-driven transaction-manager ="transactionManager" />
</beans >
6.Mybatis的配置文件
<?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 >
<package name ="com.lyx.hrs.domain" > </package >
</typeAliases >
<mappers >
<package name ="com.lyx.hrs.mapper" > </package >
</mappers >
</configuration >
(5.6)另一种-将Mybatis的配置整合到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:context ="http://www.springframework.org/schema/context"
xmlns:mybatis ="http://mybatis.org/schema/mybatis-spring"
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.xsd
http://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd" >
<context:component-scan base-package ="com.lyx.hrms" >
<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 >
<context:annotation-config />
<bean class ="com.lyx.hrms.util.MyPlaceholderConfigurer" >
<property name ="locations" value ="classpath:jdbc.properties" />
</bean >
<bean id ="dataSource" class ="com.alibaba.druid.pool.DruidDataSource" init-method ="init" destroy-method ="close" >
<property name ="url" value ="${jdbc_url}" />
<property name ="username" value ="${jdbc_user}" />
<property name ="password" value ="${jdbc_password}" />
<property name ="initialSize" value ="1" />
<property name ="minIdle" value ="1" />
<property name ="maxActive" value ="20" />
<property name ="maxWait" value ="3000" />
<property name ="timeBetweenEvictionRunsMillis" value ="60000" />
<property name ="minEvictableIdleTimeMillis" value ="300000" />
<property name ="validationQuery" value ="SELECT 'x'" />
<property name ="testWhileIdle" value ="true" />
<property name ="testOnBorrow" value ="false" />
<property name ="testOnReturn" value ="false" />
<property name ="poolPreparedStatements" value ="true" />
<property name ="maxPoolPreparedStatementPerConnectionSize" value ="20" />
<property name ="filters" value ="stat" />
</bean >
<bean id ="sqlSessionFactory" class ="org.mybatis.spring.SqlSessionFactoryBean" >
<property name ="dataSource" ref ="dataSource" />
<property name ="typeAliasesPackage" value ="com.lyx.hrms.domain" />
<property name ="mapperLocations" value ="classpath*:mapper/*.xml" />
<property name ="typeHandlersPackage" value ="com.lyx.hrms.handler" />
</bean >
<mybatis:scan base-package ="com.lyx.hrms.mapper" />
<bean id ="transactionManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name ="dataSource" ref ="dataSource" />
</bean >
<tx:annotation-driven transaction-manager ="transactionManager" />
</beans >
7.接口,接口对应的Mybaits的实现文件(持久层)
Department.java(实体类)
package com.lyx.hrs.domain;
import java.io.Serializable;
/**
* 部门表
*/
public class Department implements Serializable {
private static final long serialVersionUID = 1 L;
private Integer no;
private String name;
private String location;
public Department () {
super ();
}
public Integer getNo () {
return no;
}
public void setNo (Integer no) {
this .no = no;
}
public String getName () {
return name;
}
public void setName (String name) {
this .name = name;
}
public String getLocation () {
return location;
}
public void setLocation (String location) {
this .location = location;
}
@Override
public String toString () {
return "Department [no=" + no + ", name=" + name + ", location=" + location + "]" ;
}
}
Employee.java(实体类)
package com.lyx.hrs.domain;
import java.io.Serializable;
import java.util.Date;
/**
* 员工类实体
*/
public class Employee implements Serializable {
private static final long serialVersionUID = 1 L;
private Integer no;
private String name;
private Boolean sex;
private String job;
private Double salary;
private Date hiredate;
private Boolean status;
private String photoPath;
private String tel;
private Employee mgr;
private Department dept;
public Integer getNo () {
return no;
}
public void setNo (Integer no) {
this .no = no;
}
public String getName () {
return name;
}
public void setName (String name) {
this .name = name;
}
public Boolean getSex () {
return sex;
}
public void setSex (Boolean sex) {
this .sex = sex;
}
public String getJob () {
return job;
}
public void setJob (String job) {
this .job = job;
}
public Employee getMgr () {
return mgr;
}
public void setMgr (Employee mgr) {
this .mgr = mgr;
}
public Double getSalary () {
return salary;
}
public void setSalary (Double salary) {
this .salary = salary;
}
public Date getHiredate () {
return hiredate;
}
public void setHiredate (Date hiredate) {
this .hiredate = hiredate;
}
public Boolean getStatus () {
return status;
}
public void setStatus (Boolean status) {
this .status = status;
}
public String getPhotoPath () {
return photoPath;
}
public void setPhotoPath (String photoPath) {
this .photoPath = photoPath;
}
public String getTel () {
return tel;
}
public void setTel (String tel) {
this .tel = tel;
}
public Department getDept () {
return dept;
}
public void setDept (Department dept) {
this .dept = dept;
}
public Employee () {
super ();
}
}
DepartmentMapper.java(接口)
package com.lyx.hrs.mapper;
import java.util.List;
import com.lyx.hrs.domain.Department;
public interface DepartmentMapper {
int save(Department dept);
int deleteById(Integer no);
int update(Department dept);
Department findById(Integer id);
List<Department> findAll();
int countEmpById(Integer no);
}
DepartmentMapper.xml(与Department.java接口对应的Mybatis实现文件,Mybatis会根据该文件生成DepartmentMapper.java的实现类)
<?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.lyx.hrs.mapper.DepartmentMapper" >
<resultMap type ="department" id ="departmentResultMap" >
<id property ="no" column ="dno" />
<result property ="name" column ="dname" />
<result property ="location" column ="dloc" />
</resultMap >
<insert id ="save" parameterType ="department" >
insert into tb_dept (dno,dname,dloc)
values(#{no},#{name},#{location})
</insert >
<delete id ="deleteById" parameterType ="int" >
delete from tb_dept
where dno=#{no}
</delete >
<update id ="update" parameterType ="department" >
update tb_dept
<set >
<if test ="name!=null" > dname=#{name},</if >
<if test ="location!=null" > dloc=#{location},</if >
</set >
where dno=#{no}
</update >
<select id ="findById" resultMap ="departmentResultMap" parameterType ="int" >
select dno,dname,dloc
from tb_dept
where dno=#{no}
</select >
<select id ="findAll" resultMap ="departmentResultMap" >
select dno,dname,dloc
from tb_dept
</select >
<select id ="countEmpById" resultType ="int" >
select count(1)
from tb_emp
where dno=#{no}
</select >
</mapper >
EmployeeMapper.java(接口)
package com.lyx.hrs.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.lyx.hrs.domain.Department;
import com.lyx.hrs.domain.Employee;
/**
* 员工数据访问对象接口
*/
public interface EmployeeMapper {
int save(Employee emp);
int leaveByNo(Integer no);
int update(Employee emp);
Employee findById(Integer no);
List<Employee> findByPage(@Param ("dept" )Department dept,@Param ("offset" )Integer offset,@Param ("pageSize" )Integer pageSize);
int findTotalEmpByDept(Department dept);
}
EmployeetMapper.xml(EmployeeMapper.java接口的Mybatis的实现文件)
<?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.lyx.hrs.mapper.EmployeeMapper" >
<resultMap type ="department" id ="departmentResultMap" >
<id property ="no" column ="dno" />
<result property ="name" column ="dname" />
<result property ="location" column ="dloc" />
</resultMap >
<resultMap type ="employee" id ="mgrResultMap" >
<id property ="no" column ="mgrno" />
<result property ="name" column ="mgrname" />
</resultMap >
<resultMap type ="employee" id ="employeeResultMap" >
<id property ="no" column ="eno" />
<result property ="name" column ="ename" />
<result property ="sex" column ="esex" />
<result property ="job" column ="ejob" />
<result property ="salary" column ="esal" />
<result property ="hiredate" column ="ehiredate" />
<result property ="status" column ="estatus" />
<result property ="photoPath" column ="ephoto" />
<result property ="tel" column ="etel" />
<association property ="mgr" column ="emgr" resultMap ="mgrResultMap" />
<association property ="dept" column ="dno" resultMap ="departmentResultMap" />
</resultMap >
<insert id ="save" parameterType ="employee" >
insert into tb_emp
(eno,ename,esex,ejob,esal,ehiredate,estatus,ephoto,etel,emgr,dno)
values
(#{no},#{name},#{sex},#{job},#{salary},#{hiredate},#{status},#{photoPath},#{tel},#{mgr.no},#{dept.no})
</insert >
<update id ="leaveByNo" parameterType ="int" >
update tb_emp
set estatus=0
where eno=#{no}
</update >
<update id ="update" parameterType ="employee" >
update tb_emp
<set >
<if test ="name!=null" > ename=#{name},</if >
<if test ="job!=null" > ejob=#{job},</if >
<if test ="salary!=null" > esal=#{salary},</if >
<if test ="tel!=null" > etel=#{tel},</if >
</set >
where eno=#{no}
</update >
<select id ="findById" resultMap ="employeeResultMap" parameterType ="int" >
select t1.eno,t1.ename,t1.esex,t1.ejob,t1.esal,t1.ehiredate,t1.estatus,t1.ephoto,t1.etel,
t2.eno as mgrno,t2.ename as mgrname,t3.dno,dname,dloc
from tb_emp as t1
left outer join tb_emp as t2
on t1.emgr=t2.eno
left outer join tb_dept as t3
on t1.dno=t3.dno
where t1.eno=#{no}
</select >
<select id ="findByPage" resultMap ="employeeResultMap" >
select eno,ename,esex,ejob,estatus,etel
from tb_emp
where dno=#{dept.no} and estatus=1
limit #{offset},#{pageSize}
</select >
<select id ="findTotalEmpByDept" resultType ="int" parameterType ="department" >
select count(1)
from tb_emp
where dno=#{no}
</select >
</mapper >
8.自定义的转换器
package com.lyx.hrs.converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
public class DateConverter implements Converter <String , Date >{
@Override
public Date convert (String dateString) {
if (dateString==null ||dateString=="" ) {
throw new RuntimeException("入职时间不能为空" );
} else {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd" );
try {
return myFormat.parse(dateString);
} catch (ParseException e) {
throw new RuntimeException("字符串转日期格式出错!!!" , e);
}
}
}
}
9.杂项
Mybatis调用存储过程示例
<select id ="findAvgSalary" statementType ="CALLABLE" >
{call sp_getAvgSal(
#{name,jdbcType=VARCHAR,mode=IN},
#{avgSal,jdbcType=DOUBLE, mode=OUT}
)}
</select >
Mybatis主键回显示例
<insert id ="save" parameterType ="user" useGeneratedKeys ="true" keyProperty ="id" >
insert into tb_user(username,userpass,email,phone,realname)
values(#{username},#{password},#{email},#{phone},#{realname})
</insert >