文章目录
- SSM整合
- SSM配置整合
- SSM功能模块
SSM整合
SSM配置整合
SSM整合流程:
- 创建工程
- SSM整合
Spring
- SpringConfig
MyBatis
- MybatisConfig
- JdbcConfig
- jdbc.properties
SpringMVC
- ServletConfig
- SpringMvcConfig
创建工程
基于Maven创建项目, 选择webapp模版并补全缺失的目录
导入整合SSM的全部依赖坐标
<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>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</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>
分别创建如下图所示的包
Spring整合Mybatis
配置文件:
- SpringConfig
- JdbcConfig、jdbc.properties
- MyBatisConfig
config包下创建SpringConfig核心配置类
@Configuration // 设置为配置类
@ComponentScan({"com.chenyq.service"}) // 扫描Spring控制的bean
public class SpringConfig {
}
resource文件夹下创建jdbc.properties数据库配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db1
jdbc.username=root
jdbc.password=123456789
config包下创建JdbcConfig配置类
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;
}
}
config包下创建MyBatisConfig配置类
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setTypeAliasesPackage("com.chenyq.pojo");
return factoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.chenyq.dao");
return msc;
}
}
在SpringConfig文件中将配置的JdbcConfig、jdbc.properties、MyBatisConfig加载进来
@Configuration // 设置为配置类
@ComponentScan({"com.chenyq.service"}) // 扫描Spring控制的bean
@PropertySource("classpath:jdbc.properties") // 加载jdbc.properties配置文件
@Import({JdbcConfig.class, MyBatisConfig.class}) // 导入配置类
public class SpringConfig {
}
Spring整合SpringMVC
config包下创建一个Web容器配置类ServletConfig配置类
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[]{"/"};
}
}
config包下创建SpringMvcConfig配置类
@Configuration
@ComponentScan("com.chenyq.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
Spring事务配置
SpringConfig配置类中开启事务驱动
@Configuration // 设置为配置类
@ComponentScan({"com.chenyq.service"}) // 扫描Spring控制的bean
@PropertySource("classpath:jdbc.properties") // 加载jdbc.properties配置文件
@Import({JdbcConfig.class, MyBatisConfig.class}) // 导入配置类
@EnableTransactionManagement // 开启事务驱动
public class SpringConfig {
}
JdbcConfig创建事务管理器
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
public PlatformTransactionManager transactionManager(DataSource dataSource) {
DataSourceTransactionManager ds = new DataSourceTransactionManager();
ds.setDataSource(dataSource);
return ds;
}
}
配置SpringMvc对静态资源放行, 不拦截静态资源路径(根据需求配置)
config包下添加一个配置类SpringMvcSupport
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// 当访问静态资源路径pages时, SpringMvc不进行管理
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
// 当访问静态资源路径css时, SpringMvc不进行管理
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
// 当访问静态资源路径js时, SpringMvc不进行管理
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
// 当访问静态资源路径plugins时, SpringMvc不进行管理
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
}
}
并让SpringConfig扫描SpringMvcSupport配置类
@Configuration
@ComponentScan({"com.chenyq.controller", "com.chenyq.config"})
@EnableWebMvc
public class SpringMvcConfig {
}
到这里SSM整合就完成了, 最终目录结构如下, 下面可以添加功能模块
SSM功能模块
功能模块添加流程:
表与实体类
dao(接口+自动代理)
service(接口+实现类)
- 业务层接口测试(整合JUnit)
controller
- 表现层接口测试(PostMan)
创建数据库表和实体类:
创建tbl_book表, 并添加一些测试数据
DROP TABLE IF EXISTS `tbl_book`;
CREATE TABLE `tbl_book` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of tbl_book
-- ----------------------------
INSERT INTO `tbl_book` VALUES (1, '计算机理论', 'Spring实战 第5版', 'Spring入门经典教程,深入理解Spring原理技术内幕');
INSERT INTO `tbl_book` VALUES (2, '计算机理论', 'Spring 5核心原理与30个类手写实战', '十年沉淀之作,手写Spring精华思想');
INSERT INTO `tbl_book` VALUES (3, '计算机理论', 'Spring 5 设计模式', '深入Spring源码剖析Spring源码中蕴含的10大设计模式');
INSERT INTO `tbl_book` VALUES (4, '计算机理论', 'Spring MVC+MyBatis开发从入门到项目实战', '全方位解析面向Web应用的轻量级框架,带你成为Spring MVC开发高手');
INSERT INTO `tbl_book` VALUES (5, '计算机理论', '轻量级Java Web企业应用实战', '源码级剖析Spring框架,适合已掌握Java基础的读者');
INSERT INTO `tbl_book` VALUES (6, '计算机理论', 'Java核心技术 卷I 基础知识(原书第11版)', 'Core Java 第11版,Jolt大奖获奖作品,针对Java SE9、10、11全面更新');
INSERT INTO `tbl_book` VALUES (7, '计算机理论', '深入理解Java虚拟机', '5个维度全面剖析JVM,大厂面试知识点全覆盖');
INSERT INTO `tbl_book` VALUES (8, '计算机理论', 'Java编程思想(第4版)', 'Java学习必读经典,殿堂级著作!赢得了全球程序员的广泛赞誉');
INSERT INTO `tbl_book` VALUES (9, '计算机理论', '零基础学Java(全彩版)', '零基础自学编程的入门图书,由浅入深,详解Java语言的编程思想和核心技术');
INSERT INTO `tbl_book` VALUES (10, '市场营销', '直播就该这么做:主播高效沟通实战指南', '李子柒、李佳琦、薇娅成长为网红的秘密都在书中');
INSERT INTO `tbl_book` VALUES (11, '市场营销', '直播销讲实战一本通', '和秋叶一起学系列网络营销书籍');
INSERT INTO `tbl_book` VALUES (12, '市场营销', '直播带货:淘宝、天猫直播从新手到高手', '一本教你如何玩转直播的书,10堂课轻松实现带货月入3W+');
pojo文件夹下创建实体类Book
public class Book {
private Integer id;
private String type;
private String name;
private String description;
public Book() {
}
public Book(String type, String name, String description) {
this.type = type;
this.name = name;
this.description = description;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", type='" + type + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
}
dao层中创建一个接口BookDao, 该接口提供增删改查(查包括查全部和查单个)功能
public interface BookDao {
// 添加数据
@Insert("insert into tbl_book values(null, #{type}, #{name}, #{description})")
void save(Book book);
// 删除数据
@Delete("delete from tbl_book where id=#{id}")
void delete(Integer id);
// 修改数据
@Update("update tbl_book set type=#{type}, name=#{name}, description=#{description} where id=#{id}")
void update(Book book);
// 查询全部
@Select("select * from tbl_book")
List<Book> selectAll();
// 根据id查询
@Select("select * from tbl_book where id=#{id}")
Book selectById(Integer id);
}
service中创建一个接口BookService, 并开启事务
@Transactional // 开启事务
public interface BookService {
/**
* 增加数据
* @param book
* @return
*/
boolean save(Book book);
/**
* 删除数据
* @param id
* @return
*/
boolean delete(Integer id);
/**
* 修改数据
* @param book
* @return
*/
boolean update(Book book);
/**
* 查询全部数据
* @return
*/
List<Book> selectAll();
/**
* 根据id查询数据
* @param id
* @return
*/
Book selectById(Integer id);
}
再在service层创建一个impl包, 并创建BookService接口的一个实现类BookServiceImpl
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
public boolean save(Book book) {
bookDao.save(book);
return true;
}
public boolean delete(Integer id) {
bookDao.delete(id);
return true;
}
public boolean update(Book book) {
bookDao.update(book);
return true;
}
public List<Book> selectAll() {
return bookDao.selectAll();
}
public Book selectById(Integer id) {
return bookDao.selectById(id);
}
}
表现层controller包下创建控制器类BookController和控制器方法
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public boolean save(@RequestBody Book book) {
return bookService.save(book);
}
@DeleteMapping("/{id}")
public boolean delete(@PathVariable Integer id) {
return bookService.delete(id);
}
@PutMapping
public boolean update(@RequestBody Book book) {
return bookService.update(book);
}
@GetMapping
public List<Book> selectAll() {
return bookService.selectAll();
}
@GetMapping("/{id}")
public Book selectById(@PathVariable Integer id) {
return bookService.selectById(id);
}
}
到这里我们整合完成了SSM, 完成了对数据库增删改查的功能, 但是在真是开发中, 我们需要进行测试接口
业务层接口通过Junit测试类测试; 创建com.chenyq.service包, 在该包下创建BookServiceTest测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void testSave() {
Book book = new Book("类型aaa", "名字bbb", "描述ccc");
System.out.println(bookService.save(book));
}
@Test
public void testDelete() {
System.out.println(bookService.delete(7));
}
@Test
public void testUpdate() {
Book book = new Book("类型111", "名字222", "描述333");
book.setId(8);
System.out.println(bookService.update(book));
}
@Test
public void testSelectAll() {
System.out.println(bookService.selectAll());
}
@Test
public void testSelectById() {
System.out.println(bookService.selectById(2));
}
}
表现层接口通过PostMan进行测试