搭建SpringBoot+mybatis工程

623 阅读3分钟

这是我参与更文挑战的第25天,活动详情查看: 更文挑战

从零开始搭建 SpringBoot+mybatis+testNG 工程

1、先在本地新建一个SpringBoot+gradle项目

设置包名称和项目名称,可勾选自动导入外部包。

配置jdk 版本1.8和gradle信息,注意版本,springboot现在要求gradle是6.8.x, 6.9.x, or 7.x。

1624803685700.jpg

2、application.properties

这是SpringBoot项目的一个重要配置文件,重点配置数据库、redis、dubbo等账号连接信息。 工程创建后自动生成的该文件,也可以放置环境变量。 可以通过注解@ConfigurationProperties(prefix = "spring.test") 读取该配置文件中的账号、密码等信息。其中 「spring.test」是名称的前缀,或者通过注解@Value("${...}")。

3、数据库配置

SqlSessionTemplate是Mybatis为了接入Spring提供的Bean,实现SqlSession接口,是MyBatis的关键对象,是执行持久化操作的独享,类似于JDBC中的Connection。

SqlSessionFactory是MyBatis的关键对象,它是个单个数据库映射关系经过编译后的内存镜像。

Myabtis官网:www.mybatis.org/

//源码
public interface SqlSessionFactory {

  SqlSession openSession();//这个方法最经常用,用来创建SqlSession对象.

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

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

public class TestConfig {

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

​        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 new SqlSessionTemplate(sqlSessionFactory);

​    }

}

使用MybatisGenerter插件(自动生成DAO、DO和XML文件)

需要先配置 config.properties和generatorConfig.xml这两个文件,再运行一下MybatisGenerter插件,即可自动生成对应的DAO、DO和XML文件,当然也可以手写这几个文件。

ps:有个默认bug,重复执行表语句会导致生成的xml文件产生重复代码,并且会覆盖原来的文件,使用后要注意把generatorConfig.xml的表名注释或清除再重新执行。

配置两个文件:config.properties和generatorConfig.xml

设置数据库连接配置:/src/main/resources/mapper/config.properties

修改需要生成三个文件的表所在的数据库

# JDBC 驱动类名

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=***

# JDBC 用户名及密码

jdbc.username=***

jdbc.password=***

# 生成实体类所在的包

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

# 生成 mapper 类所在的包

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

# 生成 mapper xml 文件所在的包,默认存储在 resources 目录下

package.xml=mapper.test

需要生成DAO、DO和XML文件的表名:/src/main/resources/mapper/generatorConfig.xml

tableName里面就是数据库表名。

<table tableName="usertable">

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

</table>

运行插件,即可生成对应的三个文件。

4、配置引入dubbo接口的文件

再通过 @Autowired (根据类型匹配)或者 @Resouce(根据名字匹配)在类文件中注入bean。

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

  @Reference(retries = 0)

  private TestUserApi testUserApi;

  @Bean(name = "testUserApi")

  public TestUserApi getTestUserApi() {

 	return testUserApi;

  }
5、启动类

springboot项目会在启动类通过 @ComponentScan 来扫描对应的dubbo接口实现类,并装配到spring容器中。

@SpringBootApplication
@ComponentScan(basePackages = "com.test")
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}
6、测试脚本

注意继承 AbstractTestNGSpringContextTests ,并使用 SpringBootTest 注解。

@SpringBootTest
@Slf4j
public class DemoTest extends AbstractTestNGSpringContextTests {

}