記事ディレクトリ
SSM 統合
SSM 構成の統合
SSM 統合プロセス:
- プロジェクトを作成
- SSM 統合
春
- SpringConfig
マイバティス
- MybatisConfig
- JdbcConfig
- jdbc.properties
SpringMVC
- サーブレット構成
- 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 {
}
リソース フォルダーの下に 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;
}
}
構成済みの JdbcConfig、jdbc.properties、および MyBatisConfig を SpringConfig ファイルにロードします。
@Configuration // 设置为配置类
@ComponentScan({
"com.chenyq.service"}) // 扫描Spring控制的bean
@PropertySource("classpath:jdbc.properties") // 加载jdbc.properties配置文件
@Import({
JdbcConfig.class, MyBatisConfig.class}) // 导入配置类
public class SpringConfig {
}
Spring は Spring MVC を統合します
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 (インターフェース + 自動プロキシ)
サービス (インターフェース + 実装クラス)
- ビジネス層インターフェースのテスト (JUnit の統合)
コントローラ
- プレゼンテーション レイヤー インターフェイス テスト (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);
}
次に、サービス層で 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);
}
}
コントローラー クラス 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 でテストされています