# SSM整合
# 思路整理
# 框架之间的关系
spring framework(以下简称 spring)与spring mvc一样,都是管理java bean的容器.spring负责管理持久层与业务层相关的bean,也就是为dao和service提供bean,而spring mvc是为表现层提供bean,也就是为controller提供bean.spring和spring mvc也是一个父子容器的关系,spring是spring mvc的父容器,因此spring mvc可以访问spring容器,而反之则不行.两者也是高度整合的.
mybatis是持久层的框架,与spring关系不大,也是整合工作中的重点
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="top.brightzm.domain"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 数据源 -->
<property name="driver" value="org.mariadb.jdbc.Driver"/>
<property name="url" value="jdbc:mariadb://127.0.0.1:3306/spring_db"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 映射文件位置 -->
<package name="top.brightzm.dao"/>
</mappers>
</configuration>
执行sql语句也麻烦...
// 1.加载mybatis核心配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2.创建sqlsession对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 3.获取sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 4.获取mapper代理对象
BookDao bookDao = sqlSession.getMapper(BookDao.class);
// 5.调用接口方法
List<Book> books = BookDao.selectAll();
不过有了spring就一切好说~
mybatis这些什么配置统一变成bean,让spring管理去
数据源
@Bean public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(className); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; }
sqlSessionFactory
@Bean public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){ SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean(); // 设置数据源 sessionFactoryBean.setDataSource(dataSource); // 设置实体类别名 sessionFactoryBean.setTypeAliasesPackage("top.brightzm.domain"); return sessionFactoryBean; }
映射文件扫描
@Bean public MapperScannerConfigurer mapperScannerConfigurer(){ // 映射文件扫描 MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setBasePackage("top.brightzm.dao"); return mapperScannerConfigurer; }
调用接口方法
@Autowired private BookDao bookDao; @Override public List<Book> selectAll() { List<Book> books = bookDao.selectAll(); return books; }
# 具体流程
创建工程
废话...
添加依赖
也是废话...
编写web项目入口配置类
这个不是废话
编写web项目入口配置类,当tomcat启动时自动加载spring和spring mvc配置,启动spring和spring mvc容器
编写配置类
dao domain service controller.... 吧啦吧啦
测试!!!
# 开始整合
# 添加依赖
pom.xml 文件中
# 核心依赖
spring webmvc
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.22.RELEASE</version> </dependency>
spring webmvc含有的资源
spring 和 spring mvc的全包含的,所以只要导入spring-webmvc一个依赖
# servlet
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
# json数据转换
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
# 数据源相关
spring jdbc
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.22.RELEASE</version> </dependency>
数据库连接驱动
<dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>3.0.7</version> </dependency>
druid数据库连接池
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.14</version> </dependency>
# Mybatis 相关
mybatis
<dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>3.0.7</version> </dependency>
mybatis整合spring
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency>
# 单元测试
spring test
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.22.RELEASE</version> </dependency>
junit
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency>
# 编写配置类
config目录下
# web核心配置
ServletConfig
,继承AbstractAnnotationConfigDispatcherServletInitializer
类
Abstract^抽象^Annotation^注解^Config^配置^DispatcherServlet^前置控制器^Initializer^初始化^
看下百度百科对DispatcherServlet的解释吧
DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自己定义,把拦截下来的请求,依据相应的规则分发到目标Controller来处理,是配置spring MVC的第一步。 DispatcherServlet是前端控制器设计模式的实现,提供Spring Web MVC的集中访问点,而且负责职责的分派,而且与Spring IoC容器无缝集成,从而可以获得Spring的所有好处。
继承该类之后需重写三个方法
getRootConfigClasses
获取spring配置类getServletConfigClasses
获取spring mvc配置类getServletMappings
拦截请求
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringmvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
# 数据源配置
jdbc.properties
jdbc.driverClassName=org.mariadb.jdbc.Driver
jdbc.url=jdbc:mariadb://localhost:3306/spring_db
jdbc.username=root
jdbc.password=root
JdbcConfig
配置数据源bean,还有spring的事务管理
- 为变量赋值 @Value
public class JdbcConfig {
@Value("${jdbc.driverClassName}")
private String className;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(className);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager ds = new DataSourceTransactionManager();
ds.setDataSource(dataSource);
return ds;
}
}
# Mybatis配置
MyBatisConfig
配置sqlSession工厂类SqlSessionFactoryBean
以及映射文件扫描mapperScannerConfigurer
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
// 设置数据源
sessionFactoryBean.setDataSource(dataSource);
// 设置实体类别名
sessionFactoryBean.setTypeAliasesPackage("top.brightzm.domain");
return sessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
// 映射文件扫描
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("top.brightzm.dao");
return mapperScannerConfigurer;
}
}
# Spring和Spring MVC配置
SpringConfig
没啥好说的,为service和dao提供bean容器
标识为配置类 @Configuration
扫描service所在的包 @ComponentScan
开启事务管理 @EnableTransactionManagement
读取配置文件
jdbc.properties
@PropertySource引入配置类 @Import
@Configuration @EnableTransactionManagement @ComponentScan("top.brightzm.service") @PropertySource("classpath:jdbc.properties") @Import({JdbcConfig.class,MybatisConfig.class}) public class SpringConfig { }
SpringmvcConfig
也差不多
标识为配置类 @Configuration
扫描controller所在的包 @ComponentScan
开启SpringMVC注解支持 @EnableWebMvc
@Configuration @ComponentScan("top.brightzm.controller") @EnableWebMvc public class SpringmvcConfig { }
# 功能模块
# 持久层
domain目录下模型类Book
public class Book {
private Integer id;
private String type;
private String name;
private String description;
Constructor Getter Setter .....
}
dao目录下映射接口BookDao
public interface BookDao {
@Select("SELECT * FROM tbl_book")
List<Book> selectAll();
@Select("SELECT * FROM tbl_book WHERE id = #{id}")
Book selectById(Integer id);
@Insert("INSERT INTO tbl_book VALUES (NULL,#{type},#{name},#{description})")
void add(Book book);
@Update("UPDATE tbl_book SET type=#{type}, name=#{name}, description=#{description} WHERE id = #{id}")
void update(Book book);
@Delete("DELETE FROM tbl_book WHERE id = #{id} ")
void del(Integer id);
}
# 业务层
service目录下核心业务接口 BookService
以及实现类 BookServiceImpl
- 事务管理 @Transactional
@Transactional
public interface BookService {
public List<Book> selectAll();
public Book selectById(Integer id);
public boolean add(Book book);
public boolean update(Book book);
public boolean del(Integer id);
}
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public List<Book> selectAll() {
List<Book> books = bookDao.selectAll();
return books;
}
@Override
public Book selectById(Integer id) {
Book book = bookDao.selectById(id);
return book;
}
@Override
public boolean add(Book book) {
bookDao.add(book);
return true;
}
@Override
public boolean update(Book book) {
bookDao.update(book);
return true;
}
@Override
public boolean del(Integer id) {
bookDao.del(id);
return true;
}
}
# 表现层
controller目录下控制器BookController
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@GetMapping
public List<Book> selectAll(){
List<Book> books = bookService.selectAll();
return books;
}
@GetMapping("/{id}")
public Book selectById(@PathVariable Integer id){
Book book = bookService.selectById(id);
return book;
}
@PostMapping
public void add(@RequestBody Book book){
boolean flag = bookService.add(book);
}
@PutMapping
public void update(@RequestBody Book book){
boolean flag = bookService.update(book);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Integer id){
boolean flag = bookService.del(id);
}
}
# 测试
测试类BookServiceTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void selectAll(){
List<Book> books = bookService.selectAll();
System.out.println(books);
}
@Test
public void selectById(){
Book book = bookService.selectById(1);
System.out.println(book);
}
}
有数据展示即可
完结撒花~~