前言:通过SpringDataJPA实现对数据库的增删改查
SpringDataJPA:通过提供基于JPA的Repository减少了JPA作为数据访问方案的代码量,仅仅需要编写一个接口集成下SpringDataJPA内部定义的接口即可完成简单的CRUD操作。

  1. pom.xml下引入依赖

pom.xml下引入SpringDataJPA和mysql的dependency

         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
  1. 配置application.yml文件

对数据库连接和jpa进行配置

datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: root
    driverClassName: com.mysql.jdbc.Driver
jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  1. 编写实体

编写一个Book类,属性:id,bookName,author。
运行后数据库会生成一个Book表

@Entity
public class Book {

    @Id
    @GeneratedValue
    private Integer id;

    private String bookName;

    private String author;

    public Book() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }
}
  1. 编写BookRepository接口

编写一个BookRepository接口继承JpaRepository

BookRepository extends JpaRepository
public interface BookRepository extends JpaRepository<Book,Integer>{


}
  1. 编写BookController定义路由实现对Book表的增删改查

IOC控制反转

 @Autowired
    private BookRepository bookRepository;

查询Book的列表

@GetMapping(value = "/books")
    public List<Book> bookList(){
        return bookRepository.findAll();
    }

添加一本书

@PostMapping(value = "books")
    public Book bookAdd(@RequestParam("author") String author,
                          @RequestParam("bookName") String bookName){
        Book book = new Book();
        book.setAuthor(author);
        book.setBookName(bookName);

        return bookRepository.save(book);

    }

删除一本书

@DeleteMapping(value = "/books/{id}")
    public void bookDelete(@PathVariable("id") Integer id){
        bookRepository.delete(id);

更新一本书

 @PutMapping(value = "/books/{id}")
    public Book bookUpdate(@PathVariable("id") Integer id,
                           @RequestParam("author") String author,
                           @RequestParam("bookName") String bookName){
        Book book = new Book();
        book.setId(id);
        book.setAuthor(author);
        book.setBookName(bookName);

        return bookRepository.save(book);
    }

总结:这是利用SpringDataJPA实现的对数据库增删改查功能,下一篇实现分页功能


星空
280 声望2 粉丝

« 上一篇
算法练习