SpringBoot整合JUnit--MyBatis--MyBatis-Plus--Druid

The article is transferred from the dark horse programmer SpringBoot study notes, learning URL: Dark Horse Programmer SpringBoot2 Tutorial

1. Integrate JUnit

​ The positioning of SpringBoot technology is used to simplify development, and more specifically, to simplify the development of Spring programs. So when integrating any technology, if you want to feel the effect of simplification intuitively, you must first know how the corresponding integration is done when using non-SpringBoot technology, and then see how the SpringBoot-based integration is done before you can compare Where is the simplification?

​ Let's first take a look at how Spring integrates JUnit when SpringBoot technology is not used

//加载spring整合junit专用的类运行器
@RunWith(SpringJUnit4ClassRunner.class)
//指定对应的配置信息
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTestCase {
    //注入你要测试的对象
    @Autowired
    private AccountService accountService;
    @Test
    public void testGetById(){
        //执行要测试的对象对应的方法
        System.out.println(accountService.findById(2));
    }
}

​ Among them, the core code is the first two annotations. The first annotation @RunWith is to set up Spring’s class runner dedicated to testing. Simply put, the Spring program execution program has its own set of independent ways of running programs, which cannot be provided by JUnit. The class operation method must be specified, but the format is fixed. Think about it, and specify the same thing every time. This thing is written without technical content . The second annotation @ContextConfiguration is used to set the Spring core configuration file Or configuration class, simply put, it is to load the Spring environment. You need to tell Spring where the specific environment configuration is written. Although the files loaded each time may be different, think about it carefully. If the file name is fixed, this It seems to be a fixed format. It seems that it may be a fixed format, so it is possible to write the same thing every time, and it is also a content writing without technical content

​ SpringBoot seizes the above two non-technical content writing to simplify development. If you can take the default value, you can take the default value, and if you can’t write it, don’t write it. The specific format is as follows

@SpringBootTest
class Springboot04JunitApplicationTests {
    //注入你要测试的对象
    @Autowired
    private BookDao bookDao;
    @Test
    void contextLoads() {
        //执行要测试的对象对应的方法
        bookDao.save();
        System.out.println("two...");
    }
}

​ Take a look at what the simplification has become this time, one annotation is enough, and there are no parameters, and then realize the advantages of SpringBoot integrating other technologies, just two words- simplification . Replace the previous two annotations with one annotation @SpringBootTest. As for what's going on inside? Same as before, but with default values.

​ At this time, someone asked, which configuration class or configuration file did you load? It is the bootstrap class we used to start the program earlier. If you want to manually specify the boot class, there are two ways. The first way is to use the form of attributes. Add the classes attribute to the annotation @SpringBootTest to specify the configuration class

@SpringBootTest(classes = Springboot04JunitApplication.class)
class Springboot04JunitApplicationTests {
    //注入你要测试的对象
    @Autowired
    private BookDao bookDao;
    @Test
    void contextLoads() {
        //执行要测试的对象对应的方法
        bookDao.save();
        System.out.println("two...");
    }
}

​ The second method returns to the original configuration method, still using the @ContextConfiguration annotation, and the effect is the same

@SpringBootTest
@ContextConfiguration(classes = Springboot04JunitApplication.class)
class Springboot04JunitApplicationTests {
    //注入你要测试的对象
    @Autowired
    private BookDao bookDao;
    @Test
    void contextLoads() {
        //执行要测试的对象对应的方法
        bookDao.save();
        System.out.println("two...");
    }
}

​Reminder

​ Using SpringBoot to integrate JUnit needs to ensure that the starter corresponding to the test is imported. Since this item is imported by default when the project is initialized, it is not mentioned here. In fact, it is the same as the previous learning content, just use any technology to import the corresponding starter.

Summarize

  1. Import the starter corresponding to the test
  2. The test class is decorated with @SpringBootTest
  3. Add objects to test using autowiring
  4. If the test class exists in the package or subpackage where the boot class is located, there is no need to specify the boot class
  5. If the test class does not exist in the package or subpackage where the boot class is located, you need to specify the boot class through the classes attribute

2. Integrate MyBatis

​ After integrating JUnit, let’s talk about the integration of MyBatis. This technology is used by most companies and must be mastered. If you are not familiar with Spring’s integration of MyBatis, review it carefully. The following lists all the original integration content, taking the configuration class as an example.

  • Import coordinates, MyBatis coordinates are indispensable. Spring integrates MyBatis and has its own dedicated coordinates. In addition, Spring’s jdbc coordinates for database operations are necessary, and there are mysql driver coordinates. In this example, Druid data sources are used. This is possible. don't want

    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</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>
        <!--1.导入mybatis与spring整合的jar包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!--导入spring操作数据库必选的包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
    </dependencies>
    
  • Spring core configuration

    @Configuration
    @ComponentScan("com.itheima")
    @PropertySource("jdbc.properties")
    public class SpringConfig {
    }
    
  • The bean that MyBatis will hand over to Spring to take over

    //定义mybatis专用的配置类
    @Configuration
    public class MyBatisConfig {
    //    定义创建SqlSessionFactory对应的bean
        @Bean
        public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
            //SqlSessionFactoryBean是由mybatis-spring包提供的,专用于整合用的对象
            SqlSessionFactoryBean sfb = new SqlSessionFactoryBean();
            //设置数据源替代原始配置中的environments的配置
            sfb.setDataSource(dataSource);
            //设置类型别名替代原始配置中的typeAliases的配置
            sfb.setTypeAliasesPackage("com.itheima.domain");
            return sfb;
        }
    //    定义加载所有的映射配置
        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer(){
            MapperScannerConfigurer msc = new MapperScannerConfigurer();
            msc.setBasePackage("com.itheima.dao");
            return msc;
        }
    
    }
    
  • The bean corresponding to the data source, the Druid data source is used here

    @Configuration
    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("dataSource")
        public DataSource dataSource(){
            DruidDataSource ds = new DruidDataSource();
            ds.setDriverClassName(driver);
            ds.setUrl(url);
            ds.setUsername(userName);
            ds.setPassword(password);
            return ds;
        }
    }
    
  • Database connection information (properties format)

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
    jdbc.username=root
    jdbc.password=root
    

    The above format is basically a simplified format, and there are really many things to write. Let's take a look at SpringBoot's integration of MyBaits format

Step ① : When creating a module, check the technology to be used, MyBatis, because you need to operate the database, you must also check the corresponding database

insert image description here

insert image description here

Or manually import the starter of the corresponding technology and the coordinates of the corresponding database

<dependencies>
    <!--1.导入对应的starter-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Step ② : Configure the relevant information of the data source. Without this information, you don’t know which database you are connected to

#2.配置相关信息
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db
    username: root
    password: root

​ It's over, that's all, it's gone. Some people are wondering, is this the end? Yes, this is the end, SpringBoot simplifies all possible common configurations in the configuration. Next, you can write the Dao (or Mapper) required for the MyBatis program to run.

Entity class

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

Mapping interface (Dao)

@Mapper
public interface BookDao {
    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);
}

test class

@SpringBootTest
class Springboot05MybatisApplicationTests {
    @Autowired
    private BookDao bookDao;
    @Test
    void contextLoads() {
        System.out.println(bookDao.getById(1));
    }
}

​ Perfect, development has become so simple since then. Let's experience how SpringBoot integrates third-party technology, isn't it excellent? The specific internal principles will be explained in the principle chapter

​Note : The currently used SpringBoot version is 2.5.4, and the Mysql driver in the corresponding coordinate setting uses version 8x. Before the SpringBoot2.4.3 (excluding) version, there will be a small BUG, ​​that is, after the MySQL driver is upgraded to 8, it is required to configure the time zone. If it is not set, there will be problems. The solution is very simple, just add the corresponding settings on the driver url

#2.配置相关信息
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
    username: root
    password: root

​ The UTC set here is the global standard time. You can also understand it as British time. China is in the East Eighth District. You need to add 8 hours to this basis so that it can correspond to the time in China. You can also modify the configuration Instead of writing UTC, writing Asia/Shanghai can also solve this problem.

#2.配置相关信息
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=Asia/Shanghai
    username: root
    password: root

​ If you don’t want to set this thing every time, you can also modify the configuration file mysql.ini in mysql. Adding default-time-zone=+8:00 to the mysqld item can also solve this problem. In fact, there are many ways and methods, so here are so many.

​ In addition, a prompt will be given when running the program, saying that the database driver is outdated, just modify the configuration according to the prompt, abandon com.mysql.jdbc.Driver and use com.mysql.cj.jdbc.Driver instead . In the previous example, the driver has been replaced, let me explain here.

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

Summarize

  1. The integration operation needs to check the MyBatis technology, that is, import the starter corresponding to MyBatis

  2. Convert database connection related information into configuration

  3. Database SQL mapping needs to add @Mapper to be recognized by the container

  4. The MySQL 8.X driver is mandatory to set the time zone

    • Modify url, add serverTimezone setting
    • Modify the MySQL database configuration
  5. The driver class is outdated, remind you to replace it with com.mysql.cj.jdbc.Driver

3. Integrate MyBatis-Plus

​ After completing the integration of the two technologies, everyone should learn to summarize, which ones are the core of our integration? To sum it up in two words

  • Import the starter coordinates of the corresponding technology
  • Configure according to the requirements of the corresponding technology

​ Although it seems a bit hypocritical, it is indeed the reason. Next, strike while the iron is hot, and change another technique to see if it is the above two steps.

​ Next, on the basis of MyBatis, we will upgrade it and integrate MyBaitsPlus (MP for short), the technology developed by Chinese people, which is in line with the development habits of Chinese people, and whoever uses it will know. Come on, let's do the integration together

Step ① : Import the corresponding starter

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3</version>
</dependency>

Regarding this coordinate, here is a point to explain. The starters we saw before are all spring-boot-starter-? ? ? , that is to say, they are all in the following format

Spring-boot-start-***

​ And the writing of the name of this coordinate is quite special, with the name of the third-party technology first, followed by boot and starter.

starter affiliation Naming rules example
Officially provided spring-boot-starter-technical name spring-boot-starter-web
spring-boot-starter-test
provided by a third party Third-party technology name-spring-boot-starter druid-spring-boot-starter
provided by a third party Third-party technology name-boot-starter (the name of the third-party technology is too long, simplify the naming) mybatis-plus-boot-starter

Kind tips

​ Some friends want to find this name by checking the form when creating a project, don’t look it up, no. So far, the SpringBoot official website has not included this coordinate, and when our Idea created the module, we read the Spring Initializr on the SpringBoot official website, so there is no such coordinates. If you switch to Aliyun’s url to create a project, you can find the corresponding coordinates

Step ② : Configure data source related information

#2.配置相关信息
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db
    username: root
    password: root

​ No more, that’s all, the rest is to write the program of MyBaitsPlus

Mapping interface (Dao)

@Mapper
public interface BookDao extends BaseMapper<Book> {
}

​ The core is that the Dao interface inherits a BaseMapper interface, which helps developers reserve several commonly used API interfaces and simplifies the development of general API interfaces.

insert image description here

Below you can write a test class for testing, which is omitted here.

Kind tips

​ Currently, the table name definition rule of the database is the tbl_ module name. In order to correspond to the entity class, a configuration needs to be done. Friends with relevant knowledge can go to the MyBatisPlus course to learn, and only the solution is given here. Configure the application.yml file, add the following configuration, and set the common prefix name of all table names

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_		#设置所有表的通用前缀名称为tbl_

Summarize

  1. Manually add the starter corresponding to MyBatis-Plus
  2. The data layer interface uses BaseMapper to simplify development
  3. When the third-party technology to be used cannot be determined by checking, you need to manually add coordinates

4. Integrate Druid

​ Using SpringBoot to integrate 3 technologies, I found that the routines are basically the same, import the corresponding starter, and then configure it. Friends need to strengthen this idea all the time. Next, we will integrate another technology to continue to strengthen this idea.

​ When integrating MyBatis and MP earlier, the data source objects used are the default data source objects of SpringBoot. Next, we control them manually and specify a data source object, Druid.

​ When no data source is specified, our configuration is as follows:

#2.配置相关信息
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=Asia/Shanghai
    username: root
    password: root

​ Although no data source is specified at this time, according to the virtues of SpringBoot, it must have helped us choose a data source object that it thinks is the best, which is HiKari. You can view the corresponding figure through the startup log.

2021-11-29 09:39:15.202  INFO 12260 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2021-11-29 09:39:15.208  WARN 12260 --- [           main] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2021-11-29 09:39:15.551  INFO 12260 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.

​ Each row in the above information has HiKari. If you need to change the data source, it only takes two steps.

  1. Import the corresponding technical coordinates
  2. Configure to use the specified data source type

Next, switch the data source object

Step ① : Import the corresponding coordinates (note that it is the coordinates, not the starter here)

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

Step ② : Modify the configuration, there is a type attribute in the data source configuration, which is dedicated to specifying the data source type

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource

​ Here is actually a question to ask. The current data source configuration format is a general format. No matter what data source you change, you can use this form to configure it. But a new problem arises again. If the data source is configured individually, such as configuring the number of connections corresponding to the data source, there will be a new problem at this time. Are the configuration names for each data source technology the same? Certainly not. It is impossible for each manufacturer to discuss in advance and write the same name. What should I do? It is necessary to use a dedicated configuration format. At this time, the general format above cannot be used, what should I do? What else can I do? According to the general rules of SpringBoot integrating other technologies, import the corresponding starter and configure accordingly.

Step ① : Import the corresponding starter

<dependencies>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.2.6</version>
    </dependency>
</dependencies>

Step ② : Modify the configuration

spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
      username: root
      password: root

​ Pay attention to observe that in the configuration items, the url attributes are not directly configured under the datasource, but a druid node is configured first, and then the url is configured. The implication is that the attribute url is the attribute under druid, so can you think of it? In addition to these 4 general configurations, there are other configurations specific to druid. Through the prompt function, you can open the druid-related configuration check

insert image description here

​ There are more than 200 druid-related configurations. This tells you that if you want to do druid-related configurations, you can use this format. I won’t describe them here, because there are too many.

​ This is the fourth technology integration solution we have done, or the two sentences: import the corresponding starter and use the corresponding configuration . No, SpringBoot's integration of other technologies is as simple as that.

Summarize

  1. To integrate Druid, you need to import the starter corresponding to Druid
  2. Configure according to the configuration method provided by Druid
  3. Common way to integrate third-party technology
    • Import the corresponding starter
    • According to the configuration format provided, configure configuration items corresponding to non-default values

Guess you like

Origin blog.csdn.net/fj123321666/article/details/130248550