详细的描述了Spring中的SSM整合

SSM整合流程

1.创建工程

2.SSM整合

  • Spring
    • SpringConfig
  • MyBatis
    • MybatisConfig
    • JdbcConfig
    • Jdbc.properties
  • SpringMVC
    • ServletConfig
    • SpringMVCConfig

3.功能模块

  • 表与实体类
  • dao(接口+自动代理)
  • service(接口+实现类)
  • 业务层接口测试(整合JUnit)
  • mapper

设计一个简单的图书管理系统

总体思路分析

Spring整合MyBatis

  • 配置
    • SpringConfig
    • JDBCConfig、jdbc.properties
    • MyBatisconfig
  • 模型
    • Book
  • 数据层标准开发
    • BookDao
  • 业务层标准开发
    • BookService
    • BookServiceImpl
  • 测试接口
    BookServiceTest
  • 事务处理
    • 在SpringConfig中开启注解式事务驱动@EnableTransactionManagement
    • 在JdbcConfig中添加事务管理器PlatformTransactionManager
    • 在业务层接口上添加Spring事务管理

Spring整合SpringMVC

  • Web配置类(详见SSM07样例代码4)
  • SpringMVC配置类 SpringMVCConfig
  • 基于Restful的Controller开发

样例代码以及测试如下

程序框架

SSM09-01程序框架

MySQL数据库的设计(简单设计,样例较为简单,用于测试)

create database ssm_db default charset utf8mb4;

use ssm_db;

create table tbl_book (
id int not null auto_increment comment 'id',
type varchar(20) not null comment '种类',
name varchar(50) not null comment '书名',
description varchar(255) not null comment '简介',
primary key (id)
) COMMENT='商品表';

begin;
insert into tbl_book(type, name, description) values ('计算机理论', 'Spring实战第一版', 'Spring经典教程1');
insert into tbl_book(type, name, description) values ('计算机理论', 'Spring实战第二版', 'Spring经典教程2');
insert into tbl_book(type, name, description) values ('计算机理论', 'Spring实战第三版', 'Spring经典教程3');
insert into tbl_book(type, name, description) values ('计算机理论', 'Spring实战第四版', 'Spring经典教程4');
insert into tbl_book(type, name, description) values ('计算机理论', 'Spring实战第五版', 'Spring经典教程5');
insert into tbl_book(type, name, description) values ('计算机理论', 'Spring实战第六版', 'Spring经典教程6');
insert into tbl_book(type, name, description) values ('计算机理论', 'Spring实战第七版', 'Spring经典教程7');
insert into tbl_book(type, name, description) values ('计算机理论', 'Spring实战第八版', 'Spring经典教程8');
insert into tbl_book(type, name, description) values ('计算机理论', 'Spring实战第九版', 'Spring经典教程9');
insert into tbl_book(type, name, description) values ('市场营销', '市场营销第一版', '市场营销教程1');
insert into tbl_book(type, name, description) values ('市场营销', '市场营销第二版', '市场营销教程2');
insert into tbl_book(type, name, description) values ('市场营销', '市场营销第三版', '市场营销教程3');
commit;

详细的代码放到了github,网址如下,需要自取:

小型的SSM图书管理系统

简单的使用postman对其中的增删改查功能进行了测试

SSM09-02postman测试

具体代码如下(较为冗长,用于本人复习和调试)

Config模块

JdbcConfig

package com.wang.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

public class JdbcConfig {

@Value("${jdbc.driver}")
private String driver;
@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(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}

@Bean
// 2.事务管理器
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager ds = new DataSourceTransactionManager();
ds.setDataSource(dataSource);
return ds;
}
}

MybatisConfig

package com.wang.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class MybatisConfig {

@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setTypeAliasesPackage("com.wang.domain");
return factoryBean;
}

@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.wang.dao");
return msc;
}
}

ServletConfig

package com.wang.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}

protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}

protected String[] getServletMappings() {
return new String[]{"/"};
}
}

SpringConfig

package com.wang.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ComponentScan("com.wang.service")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
// 1.开启注解式事务驱动
@EnableTransactionManagement
public class SpringConfig {

}

SpringMVCConfig

package com.wang.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan("com.wang.controller")
@EnableWebMvc
public class SpringMvcConfig {
}

Controller(表现层)

BookController

package com.wang.controller;

import com.wang.domain.Book;
import com.wang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

@Autowired
private BookService bookService;

@PostMapping
public boolean save(@RequestBody Book book) {
return bookService.save(book);
}

@PutMapping
public boolean update(@RequestBody Book book) {
return bookService.update(book);
}

@DeleteMapping("/{id}")
public boolean delete(@PathVariable Integer id) {
return bookService.delete(id);
}

@GetMapping("/{id}")
public Book getById(@PathVariable Integer id) {
return bookService.getById(id);
}

@GetMapping
public List<Book> getAll() {
return bookService.getAll( );
}
}

dao(持久层/持久层)

BookDao

package com.wang.dao;

import com.wang.domain.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface BookDao {
@Insert("insert into ssm_db.tbl_book(type, name, description) values (#{type}, #{name}, #{description})")
public void save(Book book);
@Update("update ssm_db.tbl_book set type=#{type}, name=#{name}, description=#{description} where id = #{id}")
public void update(Book book);
@Delete("delete from ssm_db.tbl_book where id=#{id}")
public void delete(Integer id);
@Select("select * from ssm_db.tbl_book where id=#{id}")
public Book getById(Integer id);
@Select("select * from ssm_db.tbl_book")
public List<Book> getAll();
}

Service(业务层)

BookService

package com.wang.service;

import com.wang.domain.Book;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author Wang
*/


@Transactional
public interface BookService {

/**
* 保存
* @param book
* @return
*/
public boolean save(Book book);

/**
* 修改
* @param book
* @return
*/
public boolean update(Book book);

/**
* 根据id删除
* @param id
* @return
*/
public boolean delete(Integer id);

/**
* 根据id查找
* @param id
* @return
*/
public Book getById(Integer id);

/**
* 查找全部
*
* @return
*/
public List<Book> getAll();
}

BookServiceImpl

package com.wang.service.impl;

import com.wang.dao.BookDao;
import com.wang.domain.Book;
import com.wang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {

@Autowired
private BookDao bookDao;

public boolean save(Book book) {
bookDao.save(book);
return true;
}

public boolean update(Book book) {
bookDao.update(book);
return true;
}

public boolean delete(Integer id) {
bookDao.delete(id);
return true;
}

public Book getById(Integer id) {
return bookDao.getById(id);
}

public List<Book> getAll() {
return bookDao.getAll();
}
}

Domain(实体类)

Book

package com.wang.domain;

public class Book {
private Integer id;
private String type;
private String name;
private String description;


public Book() {
}

public Book(Integer id, String type, String name, String description) {
this.id = id;
this.type = type;
this.name = name;
this.description = description;
}

/**
* 获取
* @return id
*/
public Integer getId() {
return id;
}

/**
* 设置
* @param id
*/
public void setId(Integer id) {
this.id = id;
}

/**
* 获取
* @return type
*/
public String getType() {
return type;
}

/**
* 设置
* @param type
*/
public void setType(String type) {
this.type = type;
}

/**
* 获取
* @return name
*/
public String getName() {
return name;
}

/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}

/**
* 获取
* @return description
*/
public String getDescription() {
return description;
}

/**
* 设置
* @param description
*/
public void setDescription(String description) {
this.description = description;
}

public String toString() {
return "Book{id = " + id + ", type = " + type + ", name = " + name + ", description = " + description + "}";
}
}

测试类

BookServiceTest

package wang;

import com.wang.config.SpringConfig;
import com.wang.domain.Book;
import com.wang.service.BookService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class )
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {

@Autowired
private BookService bookService;

@Test
public void testGetById() {
Book book = bookService.getById(1);
System.out.println(book);
}

@Test
public void testGetAll() {
List<Book> books = bookService.getAll();
System.out.println(books);
}

}

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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SSMtest</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SSMtest Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>

<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>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>