一、配置文件方式
创建maven项目,打包方式为war
pom.xml文件
4.0.0
com.xx
ssm
0.0.1-SNAPSHOT
war
5.2.8.RELEASE
org.springframework
spring-context
${spring.version}
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.aspectj
aspectjweaver
1.8.7
com.fasterxml.jackson.core
jackson-databind
2.9.0
org.mybatis
mybatis
3.5.1
org.mybatis
mybatis-spring
2.0.0
mysql
mysql-connector-java
5.1.6
javax.servlet
javax.servlet-api
4.0.0
provided
org.apache.maven.plugins
maven-war-plugin
3.3.1
1、实体类
package com.xx.ssm.po;
public class Dept {
private Integer deptno;
private String dname;
private String loc;
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
@Override
public String toString() {
return "Dept [deptno=" + deptno + ", dname=" +
dname + ", loc=" + loc + "]";
}
}
2、创建dao层接口
package com.xx.ssm.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import com.xx.ssm.po.Dept;
@Mapper
public interface DeptMapper {
@Select("select * from dept where deptno = #{deptno}")
public Dept getDeptById(Integer deptno); //注解方式实现
public List getDept(); //映射文件方式实现
}
如果想写动态复杂sql,则也可使用映射文件
DeptMapper.xml放在resources目录下的mapper文件夹下
3、创建service层接口
package com.xx.ssm.service;
import java.util.List;
import com.xx.ssm.po.Dept;
public interface DeptService {
public Dept getDeptById(Integer deptno);
public List getDept( );
}
4、创建service层实现类
package com.xx.ssm.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xx.ssm.mapper.DeptMapper;
import com.xx.ssm.po.Dept;
import com.xx.ssm.service.DeptService;
@Service
public class DeptServiceImpl implements DeptService{
@Autowired
private DeptMapper deptMapper;
@Override
public Dept getDeptById(Integer deptno) {
return deptMapper.getDeptById(deptno);
}
@Override
public List getDept() {
return deptMapper.getDept();
}
}
5、创建controller层控制器
package com.xx.ssm.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xx.ssm.po.Dept;
import com.xx.ssm.service.DeptService;
@Controller
public class DeptController {
@Autowired
private DeptService deptService;
@ResponseBody
@RequestMapping("/getDeptById")
public Dept getDeptById(Integer deptno) throws Exception{
return deptService.getDeptById(deptno);
}
@ResponseBody
@RequestMapping("/getDept")
public List getDept( ) throws Exception{
return deptService.getDept( );
}
}
6、web.xml
ssm
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:applicationContext.xml
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc-servlet.xml
springmvc
/
7、在resources目录下创建applicationContext.xml
8、在resources目录下创建springmvc-servlet.xml文件
9、在resources目录下创建db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/emp?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
二、纯注解方式
创建maven项目,打包方式为war
pom.xml文件 、.java文件、*mapper.xml均不变,
去掉 :
applicationContext.xml
springmvc-servlet.xml
db.properties
web.xml
1、创建AppInitializer类
package com.xx.ssm;
import org.springframework.web.servlet.support.
AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer{
/**
* 返回一个带有@Configuration注解的类。
* 用来创建整个应用程序的全局Spring容器。
* 也就是等同于创建applicationContext.xml容器
*/
@Override
protected Class>[] getRootConfigClasses() {
return new Class[] {RootConfig.class};
}
/**
* 返回一个带有@Configuration注解的类。
* 用来创建SpringMVC(即Web相关)的Spring容器。
* 也就是等同于创建springmvc-servlet.xml容器
*/
@Override
protected Class>[] getServletConfigClasses() {
return new Class[] {WebConfig.class};
}
//配置SpringMVC前端控制器映射路径
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
2、创建RootConfig类
package com.xx.ssm;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.sql.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
@ComponentScan(basePackages={"com.xx.ssm.service"})//@ComponentScan用于扫描通用组件,这里用来扫描Service组件
@MapperScan(basePackages="com.xx.ssm.mapper")//@MapperScan用于扫描Mapper组件
public class RootConfig {
@Bean//创建dataSource组件并放入Spring容器
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/emp?characterEncoding=utf-8");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
@Bean//创建SqlSessionFactory组件并放入Spring容器
public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException{
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
sqlSessionFactoryBean.setMapperLocations(resolveMapperLocations());//参数调用下面方法,获取映射文件位置
sqlSessionFactoryBean.setTypeAliasesPackage("com.xx.ssm.po");//定义实体类别名
return sqlSessionFactoryBean;
}
//复杂动态sql写在对应的映射文件里会方便,这个方法主要给上面的setMapperLocations()方法提供参数,找到对应映射文件位置用的
public Resource[] resolveMapperLocations() throws IOException {
ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
List mapperLocations = new ArrayList();
mapperLocations.add("classpath*:mapper/*.xml");
List resources = new ArrayList();
if (mapperLocations != null) {
for (String mapperLocation : mapperLocations) {
Resource[] mappers = resourceResolver.getResources(mapperLocation);
resources.addAll(Arrays.asList(mappers));
}
}
return resources.toArray(new Resource[resources.size()]);
}
@Bean //创建PlatformTransactionManager组件并放入Spring容器
public PlatformTransactionManager transactionManager(DataSource dataSource){
//dataSource也可以通过参数注入
return new DataSourceTransactionManager(dataSource());
}
}
3、创建WebConfig类
package com.xx.ssm;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc //等同于 Controller组件
@ComponentScan(basePackages={"com.xx.ssm.controller"})
//用于扫描通用组件,这里用来扫描Controller组件
public class WebConfig{ }
测试数据
drop TABLE emp;
drop TABLE dept;
drop TABLE salgrade;
create table dept
(
deptno integer(4) not null,
dname varchar(14),
loc varchar(13)
);
alter table dept add constraint pk_dept primary key (deptno);
create table emp
(
empno integer(4) not null,
ename varchar(10),
job varchar(9),
mgr integer(4),
hiredate date,
sal decimal(7,2),
comm decimal(7,2),
deptno integer(2)
);
alter table emp add constraint pk_emp primary key (empno);
alter table emp add constraint fk_deptno foreign key (deptno) references dept (deptno);
create table salgrade
(
grade integer(1),
losal decimal(7,2),
hisal decimal(7,2)
);
insert into DEPT (DEPTNO, DNAME, LOC) values (10, 'ACCOUNTING', 'NEW YORK');
insert into DEPT (DEPTNO, DNAME, LOC) values (20, 'RESEARCH', 'DALLAS');
insert into DEPT (DEPTNO, DNAME, LOC) values (30, 'SALES', 'CHICAGO');
insert into DEPT (DEPTNO, DNAME, LOC) values (40, 'OPERATIONS', 'BOSTON');
insert into SALGRADE (GRADE, LOSAL, HISAL) values (1, 700, 1200);
insert into SALGRADE (GRADE, LOSAL, HISAL) values (2, 1201, 1400);
insert into SALGRADE (GRADE, LOSAL, HISAL) values (3, 1401, 2000);
insert into SALGRADE (GRADE, LOSAL, HISAL) values (4, 2001, 3000);
insert into SALGRADE (GRADE, LOSAL, HISAL) values (5, 3001, 9999);
-- 下面要特别注意,%d-%m-%Y 里的 d 和 m 一定要小写
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7369, 'SMITH', 'CLERK', 7902, STR_TO_DATE('17-12-1980', '%d-%m-%Y'), 800.00, null, 20);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7499, 'ALLEN', 'SALESMAN', 7698, STR_TO_DATE('20-02-1981', '%d-%m-%Y'), 1600.00, 300.00, 30);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7521, 'WARD', 'SALESMAN', 7698, STR_TO_DATE('22-02-1981', '%d-%m-%Y'), 1250.00, 500.00, 30);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7566, 'JONES', 'MANAGER', 7839, STR_TO_DATE('02-04-1981', '%d-%m-%Y'), 2975.00, null, 20);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7654, 'MARTIN', 'SALESMAN', 7698, STR_TO_DATE('28-09-1981', '%d-%m-%Y'), 1250.00, 1400.00, 30);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7698, 'BLAKE', 'MANAGER', 7839, STR_TO_DATE('01-05-1981', '%d-%m-%Y'), 2850.00, null, 30);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7782, 'CLARK', 'MANAGER', 7839, STR_TO_DATE('09-06-1981', '%d-%m-%Y'), 2450.00, null, 10);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7788, 'SCOTT', 'ANALYST', 7566, STR_TO_DATE('19-04-1987', '%d-%m-%Y'), 3000.00, null, 20);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7839, 'KING', 'PRESIDENT', null, STR_TO_DATE('17-11-1981', '%d-%m-%Y'), 5000.00, null, 10);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7844, 'TURNER', 'SALESMAN', 7698, STR_TO_DATE('08-09-1981', '%d-%m-%Y'), 1500.00, 0.00, 30);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7876, 'ADAMS', 'CLERK', 7788, STR_TO_DATE('23-05-1987', '%d-%m-%Y'), 1100.00, null, 20);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7900, 'JAMES', 'CLERK', 7698, STR_TO_DATE('03-12-1981', '%d-%m-%Y'), 950.00, null, 30);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7902, 'FORD', 'ANALYST', 7566, STR_TO_DATE('03-12-1981', '%d-%m-%Y'), 3000.00, null, 20);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values (7934, 'MILLER', 'CLERK', 7782, STR_TO_DATE('23-01-1982', '%d-%m-%Y'), 1300.00, null, 10);