JdbcTemplate整合(SpringBoot)

  • 第一步:导入依赖
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.17</version>
    </dependency>

第二步

public class Book {
    private Integer id;
    private String name;
    private String author;
    private Float price;
//省略getter/setter
  • 第三步:实现dao
@Repository
public class BookDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public int addBook(Book book){
        return jdbcTemplate.update("insert into book(name,author) values(?,?)",book.getName(),book.getAuthor());
    }

    public int updateBook(Book book){
        return jdbcTemplate.update("update book set name=?,author=? where id=?",book.getName(),book.getAuthor(), book.getId());
    }

    public int deleteBookById(Integer id){
        return jdbcTemplate.update("delete from book where id=?",id);
    }

    public Book getBookById(Integer id){
        return jdbcTemplate.queryForObject("select * from book where id=?",new BeanPropertyRowMapper<>(Book.class),id);
    }

    public List<Book> getAllBooks(){
        return jdbcTemplate.query("select * from book", new BeanPropertyRowMapper<>(Book.class));
    }

}
  • 第四步:实现service
@Service
public class BookService {

    @Autowired
    BookDao bookDao;

    public int addBoot(Book book){
        return bookDao.addBook(book);
    }

    public int updateBook(Book book){
        return bookDao.updateBook(book);
    }

    public int deleteBookById(Integer id){
        return bookDao.deleteBookById(id);
    }

    public Book getBookByID(Integer id){
        return bookDao.getBookById(id);
    }

    public List<Book>getAllBooks(){
        return bookDao.getAllBooks();
    }

}
  • 第五步:实现controller
    @RestController
    public class BookController {
    
        @Autowired
        BookService bookService;
    
       @GetMapping("/bookOps")
        public void  bookOps(){
            Book b1 = new Book();
            b1.setName("西厢记");
            b1.setAuthor("王师傅");
            int i = bookService.addBoot(b1);
           System.out.println("addBoot>>>"+i);
    
           Book b2 = new Book();
           b2.setId(1);
           b2.setName("朝花夕拾");
           b2.setAuthor("鲁迅");
           int i2=bookService.updateBook(b2);
           System.out.println("updateBook>>>"+i2);
    
           Book b3=bookService.getBookByID(1);
           System.out.println("getBookByID>>>"+b3);
    
           List<Book>list = bookService.getAllBooks();
           System.out.println("getAllBooks>>>"+list);
        }
    
    
    }

     

展开阅读全文
©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值