JPA和Spring data是两个不同的范畴。
JPA是一种ORM规范,JPA和Hibernate的关系就想JDBC和JDBC驱动的关系。
下面开始创建springboot整合jpa的项目:
github:https://github.com/fengqing11/springboot-jap
项目完整结构:
创建数据库jpa,这个和之前的不同,只需要创建数据库就行,不需要创建表(会自动生成)。
创建项目:
pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>xyz.fengqing11</groupId>
<artifactId>springboot-jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-jpa</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
数据库配置,application.properties
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update
创建实体类Book.java:
- @Entry注解表示该类是一个实体类,在项目启动时根据该类生产一张表
- @Id注解表明该属性是主键
- @GeneratedValue注解表示该主键自动生成,strategy代表生成的策略,这里是自动递增
- @Column注解定义字段的属性,nullable代表是否为空
- @Transient注解表明生成表时,忽略该字段,即不生成该字段
package xyz.fengqing11.springbootjpa.pojo;
import javax.persistence.*;
@Entity(name = "t_book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "book_name", nullable = false)
private String name;
private String author;
private Float price;
@Transient
private String description;
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;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
", description='" + description + '\'' +
'}';
}
}
创建BookDao接口,继承JpaRepository:
JpaRepository中提供了一些基本的增删改查、分页查询、排序查询等。
package xyz.fengqing11.springbootjpa.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import xyz.fengqing11.springbootjpa.pojo.Book;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;
public interface BookDao extends JpaRepository<Book, Integer> {
List<Book> getBooksByAuthorStartingWith(String author);
List<Book> getBooksByPriceGreaterThan(Float price);
@Query(value = "select * from t_book where id=(select max(id) from t_book )", nativeQuery = true)
Book getMaxIdBook();
@Query(value = "select b from t_book b where b.id>:id and b.author=:author")
List<Book> getBookByIdAndAuthor(@Param("author") String author, @Param("id") Integer id);
@Query("select b from t_book b where b.id<?2 and b.name like %?1%")
List<Book> getBooksByIdAndName(String name, Integer id);
}
创建BookService:
save()方法是由JpaRepository提供的
package xyz.fengqing11.springbootjpa.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import xyz.fengqing11.springbootjpa.dao.BookDao;
import xyz.fengqing11.springbootjpa.pojo.Book;
import java.util.List;
@Service
public class BookService {
@Autowired
BookDao bookDao;
public void addBook(Book book){
bookDao.save(book);
}
public Page<Book> getBookByPage(Pageable pageable){
return bookDao.findAll(pageable);
}
public List<Book> getBooksByAuthorStartingWith(String author){
return bookDao.getBooksByAuthorStartingWith(author);
}
public List<Book> getBooksByPriceGreaterThan(Float price){
return bookDao.getBooksByPriceGreaterThan(price);
}
public Book getMaxIdBook(){
return bookDao.getMaxIdBook();
}
public List<Book> getBookByIdAndAuthor(String author,Integer id){
return bookDao.getBookByIdAndAuthor(author,id);
}
public List<Book> getBooksByIdAndName(String name,Integer id){
return bookDao.getBookByIdAndAuthor(name,id);
}
}
创建BookCOntroller
package xyz.fengqing11.springbootjpa.controller;
import com.alibaba.druid.support.json.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.fengqing11.springbootjpa.pojo.Book;
import xyz.fengqing11.springbootjpa.service.BookService;
import javax.annotation.Resource;
import java.util.List;
@RestController
public class BookController {
@Autowired
BookService bookService;
@GetMapping("/findAll")
public void findAll() {
Pageable pageable = PageRequest.of(2, 3);
Page<Book> page = bookService.getBookByPage(pageable);
System.out.println("总页数:" + page.getTotalPages());
System.out.println("总查询数:" + page.getTotalElements());
System.out.println("查询结果:" + page.getContent());
System.out.println("当前页数:" + (page.getNumber() + 1));
System.out.println("当前记录数:" + page.getNumberOfElements());
System.out.println("每页记录数:" + page.getSize());
}
@GetMapping("/search")
public void search(){
}
@GetMapping("/save")
public void save(){
Book book = new Book();
book.setAuthor("按实际嗲");
book.setName("加速度");
book.setPrice(23F);
bookService.addBook(book);
}
}
访问http://127.0.0.1:8080/findAll
运行结果:
-end-