SSM整合学习笔记

学习时间:2023年6月24日

学习来源:黑马程序员

1 整合配置

1.1 创建工程

新建一个空项目,再在空项目里新建一个模块,采用maven的webapp模板创建。

image-20230624134610254


SSM整合所需的配置文件:

Spring Mybatis SpringMVC
SpringConfig MybatisConfig ServletConfig
JdbcConfig SpringMvcConfig
jdbc.properties

项目结构:

image-20230624143306193

1.2 相关依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<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>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>

1.3 Mybatis配置

MyBatis学习笔记新版中,采用了mybatis-config.xml的方式来配置数据库和数据源:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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>
<!--设置连接数据库的环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/MyBatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--引入映射文件-->
<mappers>
<mapper resource="mappers/UserMapper.xml"/>
<!--以包为单位,将包下所有的映射文件引入核心配置文件 注意:此方式必须保证mapper接口和mapper映射文件必须在相同的包下 -->
<package name="com.hongyi.mybatis.mapper"/>
</mappers>
</configuration>

然后加载该核心配置文件,来创建SqlSessionFactoryBuilder-->SqlSessionFactory-->SqlSession,最后利用SqlSession对象通过代理模式创建接口的代理实现类对象,例如UserMapper,进行SQL的操作。


改造:MyBatis的相关bean由Spring容器来统一管理。

  • jdbc.properties:数据库连接的相关参数
1
2
3
4
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db
jdbc.username=root
jdbc.password=root
  • JdbcConfig:读取jdbc.properties的参数,通过数据源创建多个数据库连接connection,等待客户端发起连接。

image-20230624144202216

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
}
}
  • MybatisConfig:相当于核心配置文件mybatis-config.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MybatisConfig {

@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
// 设置数据源
factoryBean.setDataSource(dataSource);
factoryBean.setTypeAliasesPackage("com.hongyi.domain");
return factoryBean;
}

@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer msc = new MapperScannerConfigurer();
// Mapper接口所在的包
msc.setBasePackage("com.hongyi.dao");
return msc;
}
}

1.4 SpringMVC配置

SpringMVC学习笔记中,SpringMVC需要两个配置文件:

  • springmvc.xml:SpringMVC框架的配置文件
    • 配置要扫描注解的包
    • 配置视图解析器对象
    • 开启MVC框架注解的支持
  • web.xml:Servlet配置
    • 配置中央控制器(前端控制器)dispatcherServlet
    • 加载MVC的配置文件
    • 拦截请求,例如/:拦截所有的请求

  • SpringMvcConfig:相当于springmvc.xml
1
2
3
4
5
6
@Configuration // MVC的配置类
@ComponentScan("com.hongyi.controller") // 扫描包,控制层会使用springmvc相关注解,例如@RequestMapping等等
@EnableWebMvc // 开启MVC相关功能
public class SpringMvcConfig {

}
  • ServletConfig:相当于web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
// 根容器
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}

// 所在的容器
// 相当于加载MVC的配置文件
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}

// 拦截路径
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}

1.5 Spring配置

1
2
3
4
5
6
7
@Configuration
@ComponentScan({"com.hongyi.service"})
@PropertySource("jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})
public class SpringConfig {

}
  • @Import:导入组件
  • @PropertySource:将properties配置文件中的key/value存储到Spring的Environment中,容器中的对象可以使用${}占位符为bean的属性注入值。这里JdbcConfig使用了这些参数。

2 功能模块开发

2.1 实体类

1
2
3
4
5
6
7
8
@Data
@ToString
public class Book {
private Integer id;
private String type;
private String name;
private String description;
}

2.2 持久层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Repository
public interface BookDao {
@Insert("INSERT INTO tbl_book VALUES (null, #{type}, #{name}, #{description})")
public void save(Book book);

@Update("UPDATE tbl_book SET type=#{type}, name=#{name}, description=#{description} WHERE id=#{id}")
public void update(Book book);

@Delete("DELETE FROM tbl_book WHERE id=#{id}")
public void delete(Integer id);

@Select("SELECT * FROM tbl_book WHERE id=#{id}")
public Book getById(Integer id);

@Select("SELECT * FROM tbl_book")
public List<Book> getAll();
}

2.3 业务层

1
2
3
4
5
6
7
8
9
10
11
12
@Service
public interface BookService {
public boolean save(Book book);

public boolean update(Book book);

public boolean delete(Integer id);

public Book getById(Integer id);

public List<Book> getAll();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class BookServiceImpl implements BookService {

@Autowired
private BookDao bookDao;

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

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

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

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

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

2.3 控制层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@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();
}
}