SpringBoot中怎么使用JdbcTemplate操作数据库
本篇内容介绍了“SpringBoot中怎么使用JdbcTemplate操作数据库”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
一、创建表
CREATE TABLE `t_demo` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(120) NOT NULL,
`num` int(11) NOT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='demo表';
二、添加依赖、配置
1、首先编辑 pom.xml 文件,添加相关依赖。
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 数据库驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
2、编写配置
spring.datasource.type = com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:mysql://localhost:3306/PiaoDB?useUnicode=swater&characterEncoding=UTF-8
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
三、编写代码
1、编写实体类
@Data
@Accessors(chain = true)
public class Demo {
private Integer id;
private String name;
private Integer num;
private Date createTime;
}
2、编写Dao代码
@Repository
public class DemoDao {
@Autowired
private JdbcTemplate jdbcTemplate;
// 新增数据
public int addDemo(Demo demo) {
return jdbcTemplate.update("INSERT INTO t_demo(name, num) VALUE (?, ?)",
demo.getName(), demo.getNum());
}
// 修改数据
public int updateDemo(Demo demo) {
return jdbcTemplate.update("UPDATE t_demo SET name=?, num=? WHERE id=?",
demo.getName(), demo.getNum(), demo.getId());
}
// 删除数据
public int deleteDemoById(Integer id) {
return jdbcTemplate.update("DELETE FROM t_demo WHERE id=?", id);
}
// 获取单条数据
public Demo getDemoById(Integer id) {
return jdbcTemplate.queryForObject("SELECT * FROM t_demo WHERE id=?",
new BeanPropertyRowMapper<>(Demo.class), id);
}
// 获取多条数据
public List<Demo> getAllDemos() {
return jdbcTemplate.query("SELECT * FROM t_demo",
new BeanPropertyRowMapper<>(Demo.class));
}
}
3、编写Controller代码
@RestController
@RequestMapping("/demo")
public class DemoController {
@Autowired
private DemoDao demoDao;
@RequestMapping("")
public void test(){
// 新增数据
int num = demoDao.addDemo(new Demo().setName("piao").setNum(20));
System.out.println("插入一条数据:" + num);
// 修改数据
int num2 = demoDao.updateDemo(new Demo().setId(15).setName("piao").setNum(22));
System.out.println("更新一条数据:" + num2);
// 删除数据
int num3 = demoDao.deleteDemoById(13);
System.out.println("删除一条数据:" + num3);
// 查询单条数据
Demo demo = demoDao.getDemoById(15);
System.out.println("查询1条数据:" + demo.toString());
// 查询多条数据
List<Demo> demos = demoDao.getAllDemos();
System.out.println("查询多条数据:" + demos);
}
}
四、验证结果
相关文章