SSM integration (1) | SSM creation project configuration integration - add functional modules

SSM integration

SSM configuration integration

SSM integration process :

  1. create project
  2. SSM integration

Spring

  • SpringConfig

MyBatis

  • MybatisConfig
  • JdbcConfig
  • jdbc.properties

SpringMVC

  • ServletConfig
  • SpringMvcConfig

create project

Create a project based on Maven, select the webapp template and complete the missing directory

insert image description here

Import and integrate all dependent coordinates of 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>

Create packages as shown in the figure below

insert image description here

Spring integrates Mybatis

configuration file:

  • SpringConfig
  • JdbcConfig、jdbc.properties
  • MyBatisConfig

Create a SpringConfig core configuration class under the config package

@Configuration // 设置为配置类
@ComponentScan({
    
    "com.chenyq.service"}) // 扫描Spring控制的bean
public class SpringConfig {
    
    
}

Create the jdbc.properties database configuration file under the resource folder

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db1
jdbc.username=root
jdbc.password=123456789

Create a JdbcConfig configuration class under the config package

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;
    }
}

Create a MyBatisConfig configuration class under the config package

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;
    }
}

Load the configured JdbcConfig, jdbc.properties, and MyBatisConfig in the SpringConfig file

@Configuration // 设置为配置类
@ComponentScan({
    
    "com.chenyq.service"}) // 扫描Spring控制的bean
@PropertySource("classpath:jdbc.properties") // 加载jdbc.properties配置文件
@Import({
    
    JdbcConfig.class, MyBatisConfig.class}) // 导入配置类
public class SpringConfig {
    
    
}

Spring integrates Spring MVC

Create a Web container configuration class ServletConfig configuration class under the config package

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[]{
    
    "/"};
    }
}

Create a SpringMvcConfig configuration class under the config package

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

Spring transaction configuration

Enable transaction driver in SpringConfig configuration class

@Configuration // 设置为配置类
@ComponentScan({
    
    "com.chenyq.service"}) // 扫描Spring控制的bean
@PropertySource("classpath:jdbc.properties") // 加载jdbc.properties配置文件
@Import({
    
    JdbcConfig.class, MyBatisConfig.class}) // 导入配置类
@EnableTransactionManagement // 开启事务驱动
public class SpringConfig {
    
    
}

JdbcConfig creates a transaction manager

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;
    }
}

Configure SpringMvc to release static resources without intercepting static resource paths ( configure according to requirements )

Add a configuration class SpringMvcSupport under the config package

@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/");
    }
}

And let SpringConfig scan the SpringMvcSupport configuration class

@Configuration
@ComponentScan({
    
    "com.chenyq.controller", "com.chenyq.config"})
@EnableWebMvc
public class SpringMvcConfig {
    
    
}

At this point, the SSM integration is complete. The final directory structure is as follows, and functional modules can be added below

insert image description here

SSM function module

Function module adding process :

Tables and Entity Classes

dao (interface + automatic proxy)

service (interface + implementation class)

  • Business layer interface testing (integrating JUnit)

controller

  • Presentation Layer Interface Test (PostMan)

Create database tables and entity classes :

Create the tbl_book table and add some test data

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+');

Create an entity class Book under the pojo folder

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 + '\'' +
                '}';
    }
}

Create an interface BookDao in the dao layer, which provides the function of adding, deleting, modifying and checking (including checking all and checking a single)

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);
}

Create an interface BookService in service, and start the transaction

@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);
}

Then create an impl package in the service layer, and create an implementation class BookServiceImpl of the BookService interface

@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);
    }
}

Create a controller class BookController and controller methods under the presentation layer controller package

@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);
    }
}

So far we have integrated SSM and completed the function of adding, deleting, modifying and checking the database, but in real development, we need to test the interface

The business layer interface is tested through the Junit test class; create a com.chenyq.service package, and create a BookServiceTest test under this package

@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));
    }
}

Presentation interface is tested via PostMan

insert image description here

Guess you like

Origin blog.csdn.net/m0_71485750/article/details/128037392