This is the 25th day of my participation in Gwen Challenge

Build SpringBoot+ Mybatis +testNG project from scratch

1. Create a local SpringBoot+ Gradle project

Set the package name and project name, and select Automatic import external package.

Configure JDK version 1.8 and Gradle information. Note that springBoot now requires Gradle to be 6.8.x, 6.9.x, or 7.x.

2, application properties

This is an important configuration file of the SpringBoot project, focusing on the configuration of database, redis, Dubbo and other account connection information. This file is automatically generated after the project is created and can also place environment variables. The account number, password, and other information in this configuration file can be read through the @configurationProperties annotation (prefix = “spring.test”). Where “spring.test” is the prefix of the name, or the annotation @value (“${… } “).

3. Database configuration

SqlSessionTemplate is Mybatis to access the Bean provided by Spring and implement SqlSession interface. It is a key object of Mybatis and is exclusive to perform persistent operations, similar to JDBC Connection.

SqlSessionFactory is the key object of MyBatis. It is a compiled memory image of a single database mapping.

Myabtis website: www.mybatis.org/

/ / the source code
public interface SqlSessionFactory {

  SqlSession openSession(a);// This method is most commonly used to create a SqlSession object.

  SqlSession openSession(boolean autoCommit);
  SqlSession openSession(Connection connection);
  SqlSession openSession(TransactionIsolationLevel level);

  SqlSession openSession(ExecutorType execType);
  SqlSession openSession(ExecutorType execType, boolean autoCommit);
  SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
  SqlSession openSession(ExecutorType execType, Connection connection);

  Configuration getConfiguration(a);

}
Copy the code
@Configuration
@MapperScan(basePackages = "com.test.api.data.dao.test", sqlSessionTemplateRef = "testSqlSessionTemplate")

public class TestConfig {

​    @Bean@ConfigurationProperties(prefix = "spring.datasource.test")public DataSource testDataSource(a) {

​        return DataSourceBuilder.create().build();

​    }

​    @Beanpublic SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DataSource dataSource) throws Exception {

​        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

​        bean.setDataSource(dataSource);

​        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

​        bean.setMapperLocations(resolver.

​                getResources("classpath*:mapper/test/*.xml"));

​        bean.setTypeAliasesPackage("com.test.api.data.dos.test");

​        return bean.getObject();

​    }

​    @Beanpublic DataSourceTransactionManager testTransactionManager(@Qualifier("testDataSource") DataSource dataSource) {

​        return new DataSourceTransactionManager(dataSource);

​    }

​    @Beanpublic SqlSessionTemplate testSqlSessionTemplate(@Qualifier("testSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {

​        return newSqlSessionTemplate(sqlSessionFactory); }}Copy the code

Use the MybatisGenerter plug-in (automatically generate DAO, DO, and XML files)

Config. properties and GeneratorConfig. XML files need to be configured first, and then run MybatisGenerter plug-in to automatically generate DAO, DO and XML files. You can also write these files by hand.

Ps: There is a default bug that repeated execution of table clauses will cause the generated XML file to duplicate code and overwrite the original file. Note that the generatorConfig. XML table name should be annotated or cleared before re-execution.

Configure two files: config.properties and GeneratorConfig.xml

Set up the database connection configuration: / SRC/main/resources/mapper/config. The properties

Modify the database where the table that needs to generate three files resides

# JDBC driver class name

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=***

# JDBC user name and password

jdbc.username=***

jdbc.password=***

Generate the package where the entity class resides

package.model=com.test.api.data.dos.test

Create mapper class package

package.mapper=com.test.api.data.dao.test

Mapper XML file is stored in the resources directory by default

package.xml=mapper.test

Need to generate DAO, DO and XML file table name: / SRC/main/resources/mapper/generatorConfig. The XML

TableName is the name of the database table.

<table tableName="usertable">

<generatedKey column="epa_id" sqlStatement="Mysql" identity="true" />

</table>
Copy the code

Run the plug-in to generate the corresponding three files.

4. Configure the file importing the Dubbo interface

The bean is then injected into the class file via @AutoWired (matching by type) or @resouce (matching by name).

/src/main/java/com/test/config/dubbo/DubboConsumerConfig.java

  @Reference(retries = 0)

  private TestUserApi testUserApi;

  @Bean(name = "testUserApi")

  public TestUserApi getTestUserApi(a) {

 	return testUserApi;

  }
Copy the code
5. Start classes

The SpringBoot project scans the corresponding Dubbo interface implementation classes in the startup class via @ComponentScan and assembles them into the Spring container.

@SpringBootApplication
@ComponentScan(basePackages = "com.test")
public class TestApplication {
    public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); }}Copy the code
6. Test scripts

Note to AbstractTestNGSpringContextTests and use SpringBootTest annotation.

@SpringBootTest
@Slf4j
public class DemoTest extends AbstractTestNGSpringContextTests {}Copy the code