Spring Boot整合JdbcTemplate

前期回顾:
创建Spring Boot项目
Spring Boot项目基础配置
Spring Boot上传文件
Spring Boot全局异常处理、全局数据、参数预处理
Spring Boot自定义拦截器
Spring Boot整合Servlet、Filter和Listener
Spring Boot整合AOP

JdbcTemplate是Spring提供的JDBC的一套模板框架,目的是利用AOP技术减少了直接使用JDBC的大量重复代码。Spring Boot对JdbcTemplate提供了默认的装载配置类JdbcTemplateAutoConfiguration,部分源码为:

@Configuration
@ConditionalOnClass({DataSource.class, JdbcTemplate.class})
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
@EnableConfigurationProperties({JdbcProperties.class})
public class JdbcTemplateAutoConfiguration {
    public JdbcTemplateAutoConfiguration() {
    }

    @Configuration
    @Import({JdbcTemplateAutoConfiguration.JdbcTemplateConfiguration.class})
    static class NamedParameterJdbcTemplateConfiguration {
        NamedParameterJdbcTemplateConfiguration() {
        }

        @Bean
        @Primary
        @ConditionalOnSingleCandidate(JdbcTemplate.class)
        @ConditionalOnMissingBean({NamedParameterJdbcOperations.class})
        public NamedParameterJdbcTemplate namedParameterJdbcTemplate(JdbcTemplate jdbcTemplate) {
            return new NamedParameterJdbcTemplate(jdbcTemplate);
        }
    }

    @Configuration
    static class JdbcTemplateConfiguration {
        private final DataSource dataSource;
        private final JdbcProperties properties;

        JdbcTemplateConfiguration(DataSource dataSource, JdbcProperties properties) {
            this.dataSource = dataSource;
            this.properties = properties;
        }

        @Bean
        @Primary
        @ConditionalOnMissingBean({JdbcOperations.class})
        public JdbcTemplate jdbcTemplate() {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource);
            Template template = this.properties.getTemplate();
            jdbcTemplate.setFetchSize(template.getFetchSize());
            jdbcTemplate.setMaxRows(template.getMaxRows());
            if (template.getQueryTimeout() != null) {
                jdbcTemplate.setQueryTimeout((int)template.getQueryTimeout().getSeconds());
            }

            return jdbcTemplate;
        }
    }
}

源码解释:通过@ConditionalOnClass({DataSource.class, JdbcTemplate.class})可以看到加载此配置需要DataSource和JdbcTemplate类,并且在@ConditionalOnSingleCandidate(DataSource.class)看到DataSource需为单例,若开发者没提供JdbcOperations,Spring Boot会自动注入JdbcTemplate,由此可以发现,如果项目中要使用JdbcTemplate,只需要提供JdbcTemplate和DataSource的依赖就行。
接下来就通过一个小Demo来演示下JdbcTemplate的使用:

  • maven依赖:
<!--jdbc的Spring Boot依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--数据库连接池-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.20</version>
</dependency>
  • 配置文件
spring:
  datasource:
    #指定数据库连接池
    type: com.alibaba.druid.pool.DruidDataSource
    #连接的url,SpringBoot指的是数据名
    url: jdbc:mysql://127.0.0.1:3306/SpringBoot
    #用户名
    username: root
    #密码
    password: rootroot
  • 建库建表
create database SpringBoot default charset utf8mb4;

use SpringBoot;

drop table if exists springboot_student;

create table springboot_student(
  id bigint(20) primary key auto_increment,
  name varchar(50) not null comment '姓名',
  sex varchar(2) not null comment '性别',
  age int(2) not null comment '年龄'
)engine = innodb default charset utf8mb4 comment '学生表';

  • 定义实体类
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Student {

    private Long id;

    private String name;

    private String sex;

    private Integer age;
}
  • Dao层
import java.util.List;

import com.springboot.data.dto.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository("studentDao")
public class StudentDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public boolean add(Student student) {
        return jdbcTemplate.update("insert into springboot_student (name, sex, age) values(?,?,?)", student.getName()
                , student.getSex(), student.getAge()) > 0;
    }

    public boolean update(Student student) {
        return jdbcTemplate.update("update springboot_student set name = ?,sex = ?,age = ? where id = ?",
                student.getName(), student.getSex(), student.getAge()) > 0;
    }

    public boolean delete(Long id) {
        return jdbcTemplate.update("delete from springboot_student where id = ?", id) > 0;
    }

    public List<Student> find() {
        return jdbcTemplate.query("select * from springboot_student", new BeanPropertyRowMapper<>(Student.class));
    }
}
  • Service
import java.util.List;

import com.springboot.data.dto.Student;

public interface StudentService {

    List<Student> add(Student student);

    List<Student> update(Student student);
}

import java.util.List;

import com.springboot.data.dao.StudentDao;
import com.springboot.data.dto.Student;
import com.springboot.data.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("studentService")
public class StudentServiceImpl implements StudentService {

    @Autowired
    StudentDao studentDao;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException.class)
    @Override
    public List<Student> add(Student student) {
        studentDao.add(student);
        return studentDao.find();
    }

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException.class)
    @Override
    public List<Student> update(Student student) {
        studentDao.update(student);
        return studentDao.find();
    }
}
  • Controller
import java.util.List;

import com.springboot.data.dto.Student;
import com.springboot.data.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("student")
public class StudentController {

    @Autowired
    StudentService studentService;

    @PostMapping("/add")
    public List<Student> add(@RequestBody Student student) {
        return studentService.add(student);
    }

    @PostMapping("/update")
    public List<Student> update(@RequestBody Student student) {
        return studentService.update(student);
    }
}

演示代码中就只写了个新增和修改的API了,可以通过Postman或其它工具调用测试下。

如有不到之处,欢迎各位留言指正,不慎感激。
更多文章:
点击跳转CSDN博客
点击跳转简书博客
微信公众号:代码小搬运
更多惊喜请微信扫码关注代码小搬运公众号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于构建独立的、生产级别的Java应用程序的框架,它具有简化开发过程、提高开发效率的优势。Kingbase8是一种支持高度并发和大数据量处理的关系型数据库,它类似于Oracle数据库。 要将Kingbase8 jar包整合Spring Boot项目中,需要进行以下步骤: 1. 在项目的pom.xml文件中添加Kingbase8的依赖项。可以通过在<dependencies>标签内添加以下代码实现: ``` <dependency> <groupId>org.kingbase8</groupId> <artifactId>kingbase8-driver</artifactId> <version>版本号</version> </dependency> ``` 其中,版本号是指Kingbase8 jar包的版本号,可以根据实际情况进行调整。 2. 在Spring Boot的配置文件application.properties或application.yml中添加Kingbase8数据库的连接信息。例如,可以添加以下代码: ``` spring.datasource.url=jdbc:kingbase8://localhost:5432/databasename spring.datasource.username=username spring.datasource.password=password spring.datasource.driver-class-name=org.kingbase8.Driver ``` 其中,localhost是数据库服务器的地址,5432是数据库的端口号,databasename是数据库名称,username和password是数据库的用户名和密码。 3. 在Spring Boot项目的代码中使用Kingbase8进行数据库操作。可以使用JdbcTemplate或者MyBatis等框架来访问数据库。例如,可以使用以下代码获取数据库连接: ``` @Autowired private DataSource dataSource; public void getConnection() throws SQLException { Connection connection = dataSource.getConnection(); // 进行数据库操作 connection.close(); } ``` 需要注意的是,根据项目的需求,可以使用Kingbase8官方提供的API进行数据库操作。 通过以上步骤,就可以在Spring Boot项目中成功整合Kingbase8 jar包,实现与Kingbase8数据库的连接和操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值