第一节:Spring Data Jpa 简介
Spring-Data-Jpa
JPA(Java Persistence API)定义了一系列对象持久化的标准,目前实现这一规范的产品有Hibernate、TopLink等。
第二节:Spring Data Jpa 基本crud 实现
下面对图书的CRUD来为例子:
项目结构:

1.引入jpa和mysql驱动支持
在pom.xml上右键spring -> edit starters,勾选mysql、jpa;
可以看到pom新增依赖:mysql-connector-java、spring-boot-starter-data-jpa
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.cy</groupId>
<artifactId>HelloWorld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging> <name>HelloWorld</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
2.src/main/resources/application.yml中配置server的根路径和port、数据源、showsql等:
server:
port: 80
servlet:
context-path: / spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db_book
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
3.代码:
Book.java实体:
package com.cy.entity; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name="t_book")
public class Book { @Id
@GeneratedValue
private Integer id; @Column(length=100)
private String name; @Column(length=50)
private String author; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getAuthor() {
return author;
} public void setAuthor(String author) {
this.author = author;
} }
com.cy.dao.BookDao.java:
package com.cy.dao; import org.springframework.data.jpa.repository.JpaRepository;
import com.cy.entity.Book; public interface BookDao extends JpaRepository<Book, Integer>{ }
CRUD的BookController.java:
package com.cy.controller; import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.cy.dao.BookDao;
import com.cy.entity.Book; @Controller
@RequestMapping("/book")
public class BookController { @Resource
private BookDao bookDao; /**
* 查找所有图书
*/
@RequestMapping("/list")
public ModelAndView list(){
ModelAndView mav = new ModelAndView();
List<Book> bookList = bookDao.findAll();
mav.addObject("bookList", bookList);
mav.setViewName("bookList");
return mav;
} /**
* 添加图书
*/
@RequestMapping(value="/add", method=RequestMethod.POST)
public String add(Book book){
bookDao.save(book);
return "redirect:/book/list";
} /**
* 根据id查找图书
*/
@RequestMapping("/preUpdate/{id}")
public ModelAndView preUpdate(@PathVariable("id") Integer id){
ModelAndView mav = new ModelAndView();
mav.addObject("book", bookDao.getOne(id));
mav.setViewName("bookUpdate");
return mav;
} /**
* 修改图书
*/
@PostMapping("/update")
public String update(Book book){
bookDao.save(book); //依然是save,有id就修改,没有id就添加
return "redirect:/book/list";
} /**
* 删除图书
*/
@GetMapping("/delete")
public String delete(Integer id){
bookDao.deleteById(id);
return "redirect:/book/list";
}
}
src/main/resources/templates/bookList.ftl:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书管理</title>
</head>
<body>
<a href="/bookAdd.html">添加</a>
<table>
<tr>
<th>编号</th>
<th>图书名称</th>
<th>图书作者</th>
<th>操作</th>
</tr>
<#list bookList as book>
<tr>
<td>${book.id}</td>
<td>${book.name}</td>
<td>${book.author}</td>
<td>
<a href="/book/preUpdate/${book.id}">修改</a>
<a href="/book/delete?id=${book.id}">删除</a>
</td>
</tr>
</#list>
</table>
</body>
</html>
添加图书页面src/main/webapp/bookAdd.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/book/add" method="post">
图书名称:<input type="text" name="name"/><br/>
图书作者:<input type="text" name="author"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
修改图书页面:src/main/resources/templates/bookUpdate.ftl:
要注意修改这边要把book的id带过去,不然就成添加了;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书修改</title>
</head>
<body>
<form action="/book/update" method="post">
<input type="hidden" name="id" value="${book.id}"/>
图书名称:<input type="text" name="name" value="${book.name}"/><br/>
图书作者:<input type="text" name="author" value="${book.author}"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
测试:
1.项目启动,观察新建的表,(前提是mysql中已经新建了db_book这个数据库,因为mysql的url就是jdbc:mysql://localhost:3306/db_book);
项目启动,自动建表,t_book:
mysql> show create table t_book;
+--------+--------------------------------------
------------------------------------------------
| Table | Create Table +--------+--------------------------------------
------------------------------------------------
| t_book | CREATE TABLE `t_book` (
`id` int(11) NOT NULL auto_increment,
`author` varchar(50) default NULL,
`name` varchar(100) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+--------+--------------------------------------
------------------------------------------------
1 row in set (0.00 sec)
mysql> desc t_book;
+--------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| author | varchar(50) | YES | | NULL | |
| name | varchar(100) | YES | | NULL | |
+--------+--------------+------+-----+---------+----------------+
2.http://localhost/book/list,显示:
进行增、删、改、list操作正常;