1. Integrate JUnit
1. Spring integrates JUnit
There are two core annotations:
@RunWith(SpringJUnit4ClassRunner.class)
is to set up Spring’s class runner specifically for testing (Spring program executor has its own independent way of running the program, and cannot use the class running method provided by JUnit)@ContextConfiguration(classes = SpringConfig.class)
is used to set the Spring core configuration file or configuration class (that is, the specific environment configuration required to load the Spring environment)
//Load the spring-integrated junit-specific class runner @RunWith(SpringJUnit4ClassRunner.class) //Specify the corresponding configuration information @ContextConfiguration(classes = SpringConfig.class) public class DemoServiceTestCase {<!-- --> //Inject the object you want to test @Autowired private DemoService demoService; @Test public void testGetById(){<!-- --> //Execute the method corresponding to the object to be tested System.out.println(accountService.findById(2)); } }
2. SpringBoot integrates JUnit
SpringBoot directly simplifies the two almost fixed annotations @RunWith(SpringJUnit4ClassRunner.class)
and @ContextConfiguration(classes = SpringConfig.class)
.
package com.ty; import com.ty.service.DemoService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SpringbootDemoApplicationTests {<!-- --> @Autowired private DemoService demoService; @Test public void getByIdTest(){<!-- --> demoService.getById(); } }
Note:
Of course, if the package directory where the test class SpringbootDemoApplicationTests
is located is different from the SpringBoot startup class SpringbootDemoApplication
, JUnit will not be able to find the SpringBoot startup class at startup. Error java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
.
Solution: Adjust the package directory where the test class SpringbootDemoApplicationTests
is located to be consistent with the SpringBoot startup class SpringbootDemoApplication
, or pass @SpringBootTest(classes = SpringbootDemoApplication.class)
Specifies the SpringBoot startup class.
2. Integrate MyBatis
1. Spring integration MyBatis
-
The first choice is to introduce a series of Jars to MyBatis
<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. Import the jar package integrating mybatis and spring--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!--Required package for importing spring operation database--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.10.RELEASE</version> </dependency> </dependencies>
-
Database connection information configuration
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false jdbc.username=root jdbc.password=root
-
Define mybatis-specific configuration classes
//Define mybatis-specific configuration class @Configuration public class MyBatisConfig {<!-- --> //Define and create the bean corresponding to SqlSessionFactory @Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){<!-- --> //SqlSessionFactoryBean is provided by the mybatis-spring package and is an object dedicated to integration. SqlSessionFactoryBean sfb = new SqlSessionFactoryBean(); //Set the data source to replace the environment configuration in the original configuration sfb.setDataSource(dataSource); //Set type aliases to replace the configuration of typeAliases in the original configuration sfb.setTypeAliasesPackage("com.itheima.domain"); return sfb; } // Define loading all mapping configurations @Bean public MapperScannerConfigurer mapperScannerConfigurer(){<!-- --> MapperScannerConfigurer msc = new MapperScannerConfigurer(); msc.setBasePackage("com.itheima.dao"); return msc; } }
-
Spring core configuration
@Configuration @ComponentScan("com.itheima") @PropertySource("jdbc.properties") public class SpringConfig {<!-- --> }
-
Configure beans
@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; } }
2. SpringBoot integrates MyBatis
Compared with the above, SpringBoot is much simpler.
-
First import the starter
mybatis-spring-boot-starter
and database drivermysql-connector-java
corresponding to MyBatis<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> <version>8.0.27</version> <scope>runtime</scope> </dependency>
-
Configure data source related information
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/ty username: root password: 123
The driver class is outdated, please replace it with com.mysql.cj.jdbc.Driver
-
Configure Entity and Dao, database SQL mapping needs to add @Mapper to be recognized by the container
package com.ty.entity; import lombok.Data; @Data public class TyUser {<!-- --> private Integer id; private String name; private Integer age; }
package com.ty.dao; \t import com.ty.entity.TyUser; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; \t @Mapper public interface DemoDao {<!-- --> \t @Select("select * from ty_user where id = #{id}") public TyUser getById(Integer id); \t }
-
Through the test class, it can be called by injecting DemoService.
package com.ty; import com.ty.dao.DemoDao; import com.ty.entity.TyUser; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SpringbootDemoApplicationTests {<!-- --> @Autowired private DemoDao demoDao; @Test public void getByIdTestDao(){<!-- --> TyUser byId = demoDao.getById(1); System.out.println(byId); } }
3. Integrate MyBatis-Plus
MyBaitsPlus (MP for short), a technology developed by Chinese people, is in line with Chinese development habits
-
Import mybatis_plus starter
mybatis-plus-boot-starter
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3</version> </dependency>
-
Configure data source related information
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/ty username: root password: 123
-
Dao mapping interface and entity class
package com.example.springboot_mybatisplus_demo.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.springboot_mybatisplus_demo.entity.User; import org.apache.ibatis.annotations.Mapper; @Mapper public interface DemoDao extends BaseMapper<User> {<!-- --> }
The entity class name is consistent with the table name and can be automatically mapped. When the table name has a prefix, the common prefix of the table can be configured in application.yml.
package com.example.springboot_mybatisplus_demo.entity; import lombok.Data; @Data public class User {<!-- --> private Integer id; private String name; private Integer age; }
mybatis-plus: global-config: db-config: table-prefix: ty_ #Set the common prefix name of all tables to tbl_
-
Write a test class and inject DemoDao to call a series of methods provided by mybatis_plus. The inherited BaseMapper interface helps developers reserve several commonly used API interfaces, simplifying the development of common API interfaces.
package com.example.springboot_mybatisplus_demo; import com.example.springboot_mybatisplus_demo.dao.DemoDao; import com.example.springboot_mybatisplus_demo.entity.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SpringbootMybatisplusDemoApplicationTests {<!-- --> @Autowired private DemoDao demoDao; @Test public void getByIdTestDao(){<!-- --> User byId = demoDao.selectById(1); System.out.println(byId); } }