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); } }