1. 程式人生 > 程式設計 >SpringBoot  jdbctemplate使用方法解析

SpringBoot  jdbctemplate使用方法解析

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。