SpringBoot整合JDBC之DataSourceInitializer的原理和作用

1.1作用

1:建表语句 2:运行插入的sql语句

1.2源码解读

只要两个条件符合就执行,DataSourceInitializationMode属性,看起来是通过配置文件获取的

private boolean isEnabled() {
        DataSourceInitializationMode mode = this.properties.getInitializationMode();
        if (mode == DataSourceInitializationMode.NEVER) {
            return false;
        } else {
            return mode != DataSourceInitializationMode.EMBEDDED || this.isEmbedded();
        }
    }

    private boolean isEmbedded() {
        try {
            return EmbeddedDatabaseConnection.isEmbedded(this.dataSource);
        } catch (Exception var2) {
            logger.debug("Could not determine if datasource is embedded", var2);
            return false;
        }
    }

从指定的路径获取脚本

private List<Resource> getScripts(String propertyName, List<String> resources, String fallback) {
        if (resources != null) {
            return this.getResources(propertyName, resources, true);
        } else {
            String platform = this.properties.getPlatform();
            List<String> fallbackResources = new ArrayList();
            fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");
            fallbackResources.add("classpath*:" + fallback + ".sql");
            return this.getResources(propertyName, fallbackResources, false);
        }
    }

初始化Schema.,其第三个参数为data

void initSchema() {
      List<Resource> scripts = this.getScripts("spring.datasource.data", this.properties.getData(), "data");
      if (!scripts.isEmpty()) {
          if (!this.isEnabled()) {
              logger.debug("Initialization disabled (not running data scripts)");
              return;
          }

          String username = this.properties.getDataUsername();
          String password = this.properties.getDataPassword();
          this.runScripts(scripts, username, password);
      }

  }

进行判断,其中第三个参数为schema

 boolean createSchema() {
        List<Resource> scripts = this.getScripts("spring.datasource.schema", this.properties.getSchema(), "schema");
        if (!scripts.isEmpty()) {
            if (!this.isEnabled()) {
                logger.debug("Initialization disabled (not running DDL scripts)");
                return false;
            }

            String username = this.properties.getSchemaUsername();
            String password = this.properties.getSchemaPassword();
            this.runScripts(scripts, username, password);
        }

        return !scripts.isEmpty();
    }

从getScripts(....)可知,其中其默认的文件路径为

在2个默认路径下实现sql的建表
		classpath*:schema-all.sql 
		或者	classpath*:schema.sql
 List<String> fallbackResources = new ArrayList();
            fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");
            fallbackResources.add("classpath*:" + fallback + ".sql");

测试:在路径下新建sql文件

在这里插入图片描述

sql文件:建立一张普通表.(已实现数据库的连接)

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `departmentName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

1.1从database中可以看出已经生成了department表 注!2.0必须在配置文件中加入initialization-mode: always,不然无法生效.

![在这里插入图片描述](https://img-blog.csdnimg.cn/20200801232005573.PNG)

1.2也可以通过schema指定指定的路径而不使用其默认的文件路径[List]

spring:
  datasource:
    username: root
    password: 12xxsd
    url: jdbc:mysql://localhost:xxxx/student?useSSL=false&userUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
    initialization-mode: always
    schema:
      - classpath:department.sql

2:同理也可以操作实行

从JdbcTemplateConfiguration中看出springboot已自动帮我们配置了jdbctemplate,我们可以直接使用即可.

在这里插入图片描述

@RestController
public class ControllerTest {

    @Autowired
    JdbcTemplate jdbcTemplate;
    @RequestMapping("/hello")
    public Map<String, Object> hello(){

        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select *from account");
        System.out.println(maps);
        return maps.get(0);//返回第一条
    }
}

总结

1:**在2个默认路径下实现sql的建表**
		classpath*:schema-all.sql 
		或者	classpath*:schema.sql

2必须配置initialization-mode: always
3可修改其访问文件名:schema:
- classpath:department.sql
4.springboot已自动配置Template可直接使用.进行执行sql

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot整合MyBatis-Plus非常简单,可以按照以下步骤进行操作: 1. 添加MyBatis-Plus和相关依赖:在`pom.xml`文件中添加以下依赖: ```xml <dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- MyBatis-Plus Starter --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>最新版本号</version> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> ``` 自行替换`最新版本号`为MyBatis-Plus的最新版本号。 2. 配置数据源信息:在`application.properties`(或`application.yml`)文件中配置数据库连接信息,例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 创建实体类和Mapper接口:创建与数据库表对应的实体类,使用`@TableName`注解指定表名,然后创建对应的Mapper接口,继承自`BaseMapper`。 ```java @TableName("user") // 指定对应的表名 public class User { private Long id; private String name; // getter和setter方法省略... } public interface UserMapper extends BaseMapper<User> { } ``` 4. 编写业务逻辑:可以创建Service层来封装业务逻辑,使用`@Service`注解标记为Spring的Bean。 ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User getUserById(Long id) { return userMapper.selectById(id); } // 其他业务方法... } ``` 5. 使用MyBatis-Plus提供的API:MyBatis-Plus提供了丰富的API,可以方便地操作数据库,例如查询、插入、更新和删除等操作。 ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users/{id}") public User getUser(@Pa

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值