标签:数据库 upd default value ret art jdb 功能 数据
Spring为传统的jdbc API进行封装,简化持久层操作,虽然jdbcTemplate很灵活,但和ORM框架相比jdbcTemplate功能就显得力不从心了,学习jdbcTemplate是为学习ORM框架做铺垫
<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>
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
/** * @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; } }
@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()); } }
@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); } }
标签:数据库 upd default value ret art jdb 功能 数据
原文地址:https://www.cnblogs.com/wdh01/p/12814171.html