SpringBoot jdbctemplate使用方法解析
程序员文章站
2023-02-17 16:05:26
spring为传统的jdbc api进行封装,简化持久层操作,虽然jdbctemplate很灵活,但和orm框架相比jdbctemplate功能就显得力不从心了,学习jdbctemplate是为学习o...
spring为传统的jdbc api进行封装,简化持久层操作,虽然jdbctemplate很灵活,但和orm框架相比jdbctemplate功能就显得力不从心了,学习jdbctemplate是为学习orm框架做铺垫
orm:对象关系映射 o:对象 r:关系 m:映射
下面简单介绍下 springboot 应用中如何使用 jdbctemplate 对数据库进行操作;
1、使用 idea 创建 springboot 项目,引入数据库连接依赖:
<dependency> <groupid>com.alibaba</groupid> <artifactid>druid-spring-boot-starter</artifactid> <version>1.1.10</version> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>5.1.15</version> </dependency>
2、mysql 数据库建测试表
create table `book` ( `book_id` int(11) not null auto_increment, `book_name` varchar(200) default null, `price` int(11) default null, primary key (`book_id`) ) engine=innodb auto_increment=6 default charset=utf8
3、创建 bean
/** * @author wdh01 * @create 2020-04-29 23:59 */ public class book { private integer id; private string book_name; private double price; public integer getid() { return id; } public void setid(integer id) { this.id = id; } public string getbook_name() { return book_name; } public void setbook_name(string book_name) { this.book_name = book_name; } public double getprice() { return price; } public void setprice(double price) { this.price = price; } }
4、编写 service
@service public class bookservice { @autowired jdbctemplate jdbctemplate; //insert public integer addbook(book book) { return jdbctemplate.update("insert book (book_name,price) values (?,?)", book.getbook_name(), book.getprice()); } //update 操作 public integer updatebook(book book) { return jdbctemplate.update("update book set price = ? where book_id = ?", book.getprice(),book.getid()); } //delete public integer deletebook(book book) { return jdbctemplate.update("delete from book where book_id = ?",book.getid()); } }
5、编写测试类
@springboottest class jdbctemplateapplicationtests { @autowired bookservice bookservice; @test void contextloads() { book book = new book(); book.setbook_name("笑傲江湖"); book.setprice(120); bookservice.addbook(book); } @test public void testupdate() { book book = new book(); book.setprice(10); book.setid(5); bookservice.updatebook(book); } @test public void testdelete() { book book = new book(); book.setid(5); bookservice.deletebook(book); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Java泛型机制必要性及原理解析