简单快速用SpringBoot集成JDBC

继续跟着上一节的节奏走,简单快速的集成JDBC 

首先的导入JDBC和mySQL的SpringBoot Jar文件

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

还需要在application.properties中配置如下代码:

//数据库连接地址,端口号,连接名,设置编码格式
spring.datasource.url=jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf-8
//用户名
spring.datasource.username=root
//密码
spring.datasource.password=root
//数据库驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
这是我的文件位置,名称截图:

这里写图片描述

在新建entity文件,在其里面建个StudentEntity测试实体类:

public class StudentEntity {

    //id
    private Integer id;
    //姓名
    private String name;
    //年龄
    private Integer age;
    //性别
    private String sex;
    //住址
    private String address;
    //是否逻辑删除(0:未删除,1:已删除)
    private Integer isDelete;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getIsDelete() {
        return isDelete;
    }

    public void setIsDelete(Integer isDelete) {
        this.isDelete = isDelete;
    }
}

下来就直接到service了,创建StudentService接口代码如下:

public interface StudentService {

    //写入数据
    int saveStudent();

    //查询数据
    List<StudentEntity> queryAllStudent();

    //更新数据
    int updateStudent(StudentEntity StudentEntity);

    //删除数据
    int deleteStudent(Integer id);

}

还要创建impl文件,StudentServiceImpl类,代码如下:

import com.demo.entity.StudentEntity;
import com.demo.mapper.StudentMapper;
import com.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Service("studentServices")//别名
public class StudentServiceImpl implements StudentService {


    @Resource
    private JdbcTemplate jdbcTemplate;


    //JDBC 写入数据
    @Override
    public int saveStudent() {
        //初始化属性参数
        String name = "张三";
        Integer age = 12;
        //执行写入
        int row = jdbcTemplate.update("INSERT INTO student (name,age)VALUES (?,?);", "李四", 12);
       //返回结果
       return row;
    }


    //JDBC 查询数据
    @Override
    public List<StudentEntity> queryAllStudent() {
        //SQL
        String sql = "SELECT *  FROM student WHERE is_delete=0";
        //结果
        List<StudentEntity> list = jdbcTemplate.query(sql, new RowMapper<StudentEntity>() {
            //映射每行数据  
            @Override
            public StudentEntity mapRow(ResultSet rs, int rowNum) throws SQLException {
                StudentEntity stu = new StudentEntity();
                stu.setId(rs.getInt("ID"));
                stu.setAge(rs.getInt("AGE"));
                stu.setName(rs.getString("NAME"));
                stu.setAddress(rs.getString("ADDRESS"));
                return stu;
            }

        });
        //返回结果
        return list;
    }

    //JDBC 更新数据
    @Override
    public int updateStudent(StudentEntity studentEntity) {
        //SQL
        String sql = "update tudent set name=?,address=? where id=?";
        //结果
        int row = jdbcTemplate.update(sql, new PreparedStatementSetter() {
            //映射数据
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                preparedStatement.setString(1, studentEntity.getName());
                preparedStatement.setString(2, studentEntity.getAddress());
                preparedStatement.setInt(3, studentEntity.getId());
            }
        });
        //反悔结果
        return row;
    }

    //删除数据
    @Override
    public int deleteStudent(Integer id) {
        //SQL+结果
        int resRow = jdbcTemplate.update("UPDATE student SET is_delete=1 WHERE id=?", new PreparedStatementSetter() {
            //映射数据
            @Override
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setInt(1, id);
            }
        });
        //返回结果
        return resRow;
    }
}

最后就剩controller,创建StudentControllerImpl:代码如下

import com.demo.entity.StudentEntity;
import com.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RestController
public class StudentControllerImpl {

    @Autowired
    private StudentService studentServices;

    /**
     *新增数据
     * */
    @RequestMapping("/save")
    public String save() {

       int row = studentServices.saveStudent();
       //判断结果
       if(row==-1){
            return "新增失败";
        }else{
            return "新增成功";
        }
    }

    /**
     * 查询数据
     * */
    @RequestMapping("/query")
    public String query(){
        //查寻数据
        List list = studentServices.queryAllStudent();
        //组装数据
        List newlist = new ArrayList();
        //循环取出结果
        for (int i = 0; i <list.size() ; i++) {
            //新建学生对象
            StudentEntity stu = (StudentEntity) list.get(i);
            //填充数据
            newlist.add(stu.getId());
            newlist.add(stu.getName());
            newlist.add(stu.getAge());
            newlist.add(stu.getSex());
            newlist.add(stu.getAddress());
        }
        //返回数据
        return newlist.toString();
    }


    /**
     * 更新数据
     * */
    @RequestMapping("/update")
    public String update(){
        //新建对象传递数据
        StudentEntity stu = new StudentEntity();
        stu.setId(2);
        stu.setName("尼古拉斯");
        stu.setAddress("东北");
        //执行更新操作
        int row = studentServices.updateStudent(stu);
        //判断结果
        if(row==-1){
            return "更新失败";
        }else {
            return "更新成功";
        }
    }

    /**
     * 删除数据
     * */
    @RequestMapping("/delete")
    public String delete(){
        //初始化数据
        Integer id = 3;
        //执行删除
        int row = studentServices.deleteStudent(id);
        //判断结果
        if(row==-1){
            return "删除失败";
        }else{
            return "删除成功";
        }
    }
}
 这就完事了,启动运行我的URL:localhost:8080/save, 请各位路过的大神多多指教,如有问题或者疑问请留言,
  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 Spring Boot 中集成 Sharding-JDBC 可以通过以下步骤完成: 1. 添加相关依赖:首先,在项目的 `pom.xml` 文件中添加 Sharding-JDBC 的依赖。例如,可以添加如下依赖: ```xml <dependencies> <!-- Sharding-JDBC --> <dependency> <groupId>io.shardingjdbc</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>最新版本</version> </dependency> <!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>最新版本</version> </dependency> </dependencies> ``` 2. 配置数据源:在项目的配置文件(例如 `application.yml` 或 `application.properties`)中,配置数据源的连接信息。可以配置主库和从库的数据源。例如: ```yaml spring: sharding: jdbc: datasource: names: ds-master, ds-slave1, ds-slave2 ds-master: url: jdbc:mysql://localhost:3306/db_master?useSSL=false&characterEncoding=utf8 username: root password: password driver-class-name: com.mysql.jdbc.Driver ds-slave1: url: jdbc:mysql://localhost:3306/db_slave1?useSSL=false&characterEncoding=utf8 username: root password: password driver-class-name: com.mysql.jdbc.Driver ds-slave2: url: jdbc:mysql://localhost:3306/db_slave2?useSSL=false&characterEncoding=utf8 username: root password: password driver-class-name: com.mysql.jdbc.Driver ``` 3. 配置 Sharding-JDBC:在项目的配置类中,使用 `@Configuration` 注解标记该类为配置类,并使用 `@EnableConfigurationProperties` 注解引入 Sharding-JDBC 的配置属性。然后,通过 `ShardingRuleConfiguration` 配置数据分片规则,例如指定分片策略、分片键等信息。最后,通过 `ShardingDataSource` 创建数据源,并将其注入到 Spring 容器中。例如: ```java @Configuration @EnableConfigurationProperties(ShardingProperties.class) public class ShardingJdbcConfig { @Autowired private ShardingProperties shardingProperties; @Bean public DataSource dataSource() throws SQLException { ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); // 配置分片表规则 TableRuleConfiguration tableRuleConfig = new TableRuleConfiguration(); tableRuleConfig.setLogicTable("your_table"); tableRuleConfig.setActualDataNodes("ds-master.your_table_${0..1}, ds-slave.your_table_${0..1}"); // 配置分片算法 InlineShardingStrategyConfiguration shardingStrategyConfig = new InlineShardingStrategyConfiguration(); shardingStrategyConfig.setShardingColumn("id"); shardingStrategyConfig.setAlgorithmExpression("your_table_${id % 2}"); tableRuleConfig.setTableShardingStrategyConfig(shardingStrategyConfig); shardingRuleConfig.getTableRuleConfigs().add(tableRuleConfig); // 创建 ShardingDataSource return ShardingDataSourceFactory.createDataSource( shardingProperties.getDataSourceMap(), shardingRuleConfig, new Properties() ); } } ``` 4. 使用 Sharding-JDBC:在 Service 或 Repository 类中,使用 `@Autowired` 注解注入数据源,并使用 SQL 操作数据库。Sharding-JDBC 会根据配置的分片规则自动将数据分发到对应的数据源上。例如: ```java @Service public class UserService { @Autowired private DataSource dataSource; public List<User> getUsers() { // 使用 dataSource 执行查询操作 // ... } public void addUser(User user) { // 使用 dataSource 执行插入操作 // ... } // 其他方法... } ``` 以上就是在 Spring Boot 中集成 Sharding-JDBC 的步骤。配置完成后,你可以在需要使用数据库的地方注入数据源并进行数据库操作。请注意,以上示例是基于 Sharding-JDBC 4.x 版本的,如果你使用的是其他版本,请相应调整配置方式。另外,示例中的配置是基于 MySQL 数据库的,如果你使用的是其他数据库,请相应调整数据库驱动和连接信息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值