前言:通过SpringDataJPA
实现对数据库的增删改查
SpringDataJPA:通过提供基于JPA的Repository减少了JPA作为数据访问方案的代码量,仅仅需要编写一个接口集成下SpringDataJPA内部定义的接口即可完成简单的CRUD操作。
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>
配置
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
编写实体
编写一个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;
}
}
编写
BookRepository
接口
编写一个BookRepository接口继承JpaRepository
BookRepository extends JpaRepository
public interface BookRepository extends JpaRepository<Book,Integer>{
}
编写
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实现的对数据库增删改查功能,下一篇实现分页功能
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。