全国旗舰校区

不同学习城市 同样授课品质

北京

深圳

上海

广州

郑州

大连

武汉

成都

西安

杭州

青岛

重庆

长沙

哈尔滨

南京

太原

沈阳

合肥

贵阳

济南

下一个校区
就在你家门口
+
当前位置:首页  >  技术干货

SpringBoot整合JDBCTemplat

发布时间:2023-04-07 16:17:00
发布人:syq

  Spring Boot提供了Spring jdbc template 来简化操作数据库的流程,下面是一个使用JdbcTemplate进行增删改查的示例:

SpringBoot整合JDBCTemplat

  1、首先,在Spring Boot的pom.xml文件中添加如下依赖:


org.springframework.boot
spring-boot-starter-jdbc

   2、在application.properties中配置数据库连接信息:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456

   3、编写JdbcDemo.java:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class JdbcDemo {
@Autowired
private JdbcTemplate jdbcTemplate;

public void insert(String name) {
jdbcTemplate.update("insert into user (name) values (?)", name);
}

public void delete(int id) {
jdbcTemplate.update("delete from user where id=?", id);
}

public void update(User user) {
jdbcTemplate.update("update user set name=? where id=?", user.getName(), user.getId());
}

public User selectById(int id) {
return jdbcTemplate.queryForObject("select * from user where id=?", new Object[]{id},
(rs, rowNum) -> new User(rs.getInt("id"), rs.getString("name")));
}
}

   4、编写测试类JdbcDemoTest.java:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class JdbcDemoTest {
@Autowired
private JdbcDemo jdbcDemo;

@Test
public void test() {
// 插入一条数据
jdbcDemo.insert("Alice");

// 查询数据
User user = jdbcDemo.selectById(1);
System.out.println(user);

// 更新数据
user.setName("Bob");
jdbcDemo.update(user);

// 查询数据
user = jdbcDemo.selectById(1);
System.out.println(user);

// 删除数据
jdbcDemo.delete(1);
}
}

  以上示例中,JdbcTemplate类提供了一系列方法,如update()、query()、queryForObject()等用于执行SQL语句,参数类型为JdbcTemplate一般采用@Autowired注解自动装配。Demo中演示了基本的增删改查操作。

  最后,用Junit进行单元测试即可。

相关文章

python写入json文件?

python写入json文件?

2023-11-02
vscode设置tab为4个空格?

vscode设置tab为4个空格?

2023-11-02
更新pycharm?

更新pycharm?

2023-11-02
anaconda每次打开都要安装?

anaconda每次打开都要安装?

2023-11-02

最新文章

武汉新媒体行业公司排名

武汉新媒体行业公司排名

2023-11-01
武汉新媒体就业现状好吗

武汉新媒体就业现状好吗

2023-11-01
武汉全媒体行业发展现状及趋势

武汉全媒体行业发展现状及趋势

2023-10-31
武汉全媒体现状

武汉全媒体现状

2023-10-31
在线咨询 免费试学 教程领取