Springboot --- 配置多数据源,使用JdbcTemplate以及NamedParameterJdbcTemplate

Springboot --- 配置多数据源,使用JdbcTemplate以及NamedParameterJdbcTemplate

整理不易,不喜勿喷。谢谢

SpringBoot — 整合Ldap.
SpringBoot — 整合Spring Data JPA.
SpringBoot — 整合Elasticsearch.
SpringBoot — 整合spring-data-jpa和spring-data-elasticsearch.
SpringBoot — 整合thymeleaf.
SpringBoot — 注入第三方jar包.
SpringBoot — 整合Redis.
Springboot — 整合slf4j打印日志.
Springboot — 整合定时任务,自动执行方法.
Springboot — 配置多数据源,使用JdbcTemplate以及NamedParameterJdbcTemplate.
Sprignboot — 详解pom.xml中build和profile.
SpringBoot — 监控.
SpringBoot — 缓存Cache/Redis.
SpringBoot与Zookeeper.
Git的使用.

部分内容抄这个大神的 => Spring Boot多数据源配置之JdbcTemplate.

1.dependencys

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--influx-->
        <dependency>
            <groupId>org.influxdb</groupId>
            <artifactId>influxdb-java</artifactId>
            <version>2.15</version>
        </dependency>
    </dependencies>

2.application.properties

spring.datasource.one.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.one.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.one.jdbc-url=jdbc:sqlserver://10.xxx.xxx.xxx:1433;DatabaseName=xxxx
spring.datasource.one.username=xxxx
spring.datasource.one.password=xxxx

spring.datasource.two.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.two.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.two.jdbc-url=jdbc:sqlserver://10.xxx.xxx.xxx:1433;DatabaseName=xxxx
spring.datasource.two.username=xxxx
spring.datasource.two.password=xxx

3.Config类

@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.one")
    public DataSource dsOne(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.two")
    public DataSource dsTwo(){
        return DataSourceBuilder.create().build();
    }

}
@Configuration
public class JdbcTemplateConfig {

     @Bean
     @Primary
     public JdbcTemplate jdbcTemplateOne(@Qualifier("dsOne")DataSource dsOne){
          return new JdbcTemplate(dsOne);
     }

     @Bean
     public JdbcTemplate jdbcTemplateTwo(@Qualifier("dsTwo")DataSource dsTwo){
          return new JdbcTemplate(dsTwo);
     }
}

4.service

@Service
public class DataMapperService {

    @Autowired
    @Qualifier("jdbcTemplateOne")
    private JdbcTemplate jdbcTemplateOne;

    @Autowired
    @Resource(name = "jdbcTemplateTwo")
    private JdbcTemplate jdbcTemplateTwo;

    public List<BusinessTermEntity> getAllTerms(String sql) {
        return jdbcTemplateOne.query(sql, new BusinessTermMapper());
    }

    private class BusinessTermMapper implements RowMapper<BusinessTermEntity> {
        @Override
        public BusinessTermEntity mapRow(ResultSet resultSet, int i) throws SQLException {
        	
            BusinessTermEntity bt = new BusinessTermEntity();
            bt.setBusinessTermId(checkResultOfQueryBigInte(resultSet.getObject("business_term_id")));
            bt.setIsCurrentVersion(resultSet.getNString("is_current_version"));
            bt.setBatchStatus(resultSet.getNString("batch_status"));
            bt.setHasExtendedText(resultSet.getNString("has_extended_text"));
            bt.setEndDt(resultSet.getTimestamp("end_dt"));
            return bt;
        }
    }
@Service
public class DataPipelineService {

    @Autowired
    private DataPipelineDao dataPipelineDao;
    @Autowired
    private DataMapperService dataMapperService;
    @Value("${name}")
    private String environment;

    public Long getTermByName(String name) {
    		
				
        String getName = dataPipelineDao.getTermName("xxxx");
        List<BusinessTermEntity> allTerms = dataMapperService.getAllTerms(getName);
        long businessTermId = allTerms.get(0).getBusinessTermId().longValue();
        return businessTermId;
    }

5.NamedParameterJdbcTemplate

NamedParameterJdbcTemplate类是基于JdbcTemplate类,并对它进行了封装从而支持命名参数特性。

NamedParameterJdbcTemplate主要提供以下三类方法:execute方法、query及queryForXXX方法、update及batchUpdate方法

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Test
    void contextLoads() {
        String sql = "select count(employId) from user where deparement_id =:deptId order by age desc";
        MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
        mapSqlParameterSource.addValue("deptId", 3);
        Integer count = namedParameterJdbcTemplate.queryForObject(sql, mapSqlParameterSource, Integer.class);
    }

    //insert
    @Test
    void test() {
        User user = new User();
        user.setId(UUID.randomUUID().toString());
        user.setName("旺财");
        user.setHomeAddress("唐伯虎家");

        namedParameterJdbcTemplate.update("insert into student(id,name,home_address) values (:id,:name,:homeAddress)",
                new BeanPropertySqlParameterSource(user));
    }

    //update
    @Test
    void test1() {
        User user = new User();
        user.setId(1);
        user.setName("旺财");
        user.setHomeAddress("唐伯虎家");

        String sql = "update user set name =:name and homeAddress =:homeAddress where id = :id";
        SqlParameterSource source = new BeanPropertySqlParameterSource(user);
        namedParameterJdbcTemplate.update(sql, source);
    }


    //query entity
    @Test
    void test2() {
        User user = namedParameterJdbcTemplate.queryForObject(
                "select * from student limit 1", new HashMap<>(), new BeanPropertyRowMapper<User>(User.class));
    }

    @Test
    void test3() {
        List<User> userList = namedParameterJdbcTemplate.query(
                "select * from USER",
                new BeanPropertyRowMapper<>(User.class)
        );
    }    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Test
    void contextLoads() {
        String sql = "select count(employId) from user where deparement_id =:deptId order by age desc";
        MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
        mapSqlParameterSource.addValue("deptId", 3);
        Integer count = namedParameterJdbcTemplate.queryForObject(sql, mapSqlParameterSource, Integer.class);
    }

    //insert
    @Test
    void test() {
        User user = new User();
        user.setId(UUID.randomUUID().toString());
        user.setName("旺财");
        user.setHomeAddress("唐伯虎家");

        namedParameterJdbcTemplate.update("insert into student(id,name,home_address) values (:id,:name,:homeAddress)",
                new BeanPropertySqlParameterSource(user));
    }

    //update
    @Test
    void test1() {
        User user = new User();
        user.setId(1);
        user.setName("旺财");
        user.setHomeAddress("唐伯虎家");

        String sql = "update user set name =:name and homeAddress =:homeAddress where id = :id";
        SqlParameterSource source = new BeanPropertySqlParameterSource(user);
        namedParameterJdbcTemplate.update(sql, source);
    }


    //query entity
    @Test
    void test2() {
        User user = namedParameterJdbcTemplate.queryForObject(
                "select * from student limit 1", new HashMap<>(), new BeanPropertyRowMapper<User>(User.class));
    }

    @Test
    void test3() {
        List<User> userList = namedParameterJdbcTemplate.query(
                "select * from USER",
                new BeanPropertyRowMapper<>(User.class)
        );
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面是 SpringBoot 集成 sharding-jdbc-spring-boot-starter 并使用 yml 配置多数据源的方式 进行 分表配置的步骤: 1. 首先,在 pom.xml 文件中添加 sharding-jdbc-spring-boot-starter 依赖,如下所示: ```xml <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>${shardingsphere.version}</version> </dependency> ``` 2. 在 application.yml 配置文件中添加数据源配置,如下所示: ```yml spring: datasource: # 主数据源 master: url: jdbc:mysql://localhost:3306/db_master?serverTimezone=UTC&useSSL=false&characterEncoding=utf-8 username: root password: root # 从数据源 slave: url: jdbc:mysql://localhost:3306/db_slave?serverTimezone=UTC&useSSL=false&characterEncoding=utf-8 username: root password: root # sharding-jdbc 配置 sharding: jdbc: #配置主从数据源名称 data-sources: # 配置数据源 master: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: ${spring.datasource.master.url} username: ${spring.datasource.master.username} password: ${spring.datasource.master.password} hikari: minimum-idle: 5 maximum-pool-size: 20 auto-commit: true idle-timeout: 30000 pool-name: master # 配置数据源 slave: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: ${spring.datasource.slave.url} username: ${spring.datasource.slave.username} password: ${spring.datasource.slave.password} hikari: minimum-idle: 5 maximum-pool-size: 20 auto-commit: true idle-timeout: 30000 pool-name: slave # 配置表规则 sharding: tables: # 配置分表规则 user: actual-data-nodes: master.user_${0..2} table-strategy: inline: sharding-column: id algorithm-expression: user_${id % 3} key-generator: type: SNOWFLAKE column: id props: worker-id: 123 # 配置读写分离规则 master-slave-rules: - name: ms master-data-source-name: master slave-data-source-names: slave ``` 3. 在代码中使用数据源,如下所示: ```java @Service public class UserServiceImpl implements UserService { @Autowired private JdbcTemplate jdbcTemplate; @Override public void addUser(User user) { String sql = "insert into user(id, name, age) values(?, ?, ?)"; Object[] params = new Object[]{user.getId(), user.getName(), user.getAge()}; jdbcTemplate.update(sql, params); } @Override public List<User> getUsers() { String sql = "select * from user"; List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class)); return userList; } } ``` 希望这些步骤能够帮助你集成 sharding-jdbc-spring-boot-starter 并使用 yml 配置多数据源的方式进行分表配置。如果你有更多的问题,欢迎随向我提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百世经纶『一页書』

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值