SpringBoot--整合JPA

SpringBoot整合JPA

创建工程并导入依赖


<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.0modelVersion>

    <groupId>pers.zhanggroupId>
    <artifactId>springboot_jpaartifactId>
    <version>1.0-SNAPSHOTversion>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.5.9.RELEASEversion>
        <relativePath/> 
    parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.9version>
        dependency>
    dependencies>
project>

配置文件

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql:///chapter05
    username: root
    password: 123456
  jpa:
    show-sql: true #是否打印sql
    database: mysql #JPA对应的数据库
    hibernate:
      ddl-auto: update #无表创建表

实体类

package pers.zhang.entity;

import javax.persistence.*;

/**
 * @author zhang
 * @date 2019/12/18 - 21:59
 */

/**
 * @Entity 表示该类是一个实体类,在项目启动时会根据该类自动生成一张表,表的名称即@Entity注解中name的值,如果不配置name,默认表名为类名。
 *
 * 所有的实体类都要有主键,@Id注解表示该属性是一个主键,@GeneratedValue注解表示主键自动生成,strategy表示主键的生成策略。
 *
 * 默认情况下,生成的表中字段名称就是实体类中的属性名称,通过@Column注解可以定制生成的字段名,name可以表示该属性对应的数据表中字段的名称,
 * nullable表示该字段是否非空
 *
 * @Transient 注解表示在生成数据库中的表时,该属性被忽略,即不生成对应的字段。
 */
@Entity(name = "t_book")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "book_name", nullable = false)//nullable是否非空
    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 + '\'' +
                '}';
    }
}

Dao

public interface BookDao extends JpaRepository<Book, Integer>, JpaSpecificationExecutor<Book> {

    /*
        查询以某个字符开始的所有书
     */
    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("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);
}

Service

package pers.zhang.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 pers.zhang.dao.BookDao;
import pers.zhang.entity.Book;

import java.util.List;

/**
 * @author zhang
 * @date 2019/12/18 - 22:18
 */
@Service
public class BookService {
    @Autowired
    BookDao bookDao;


    public void addBook(Book book){
        bookDao.save(book);
    }

    public Page<Book> getBooksByPage(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.getBooksByIdAndName(name, id);
    }
}

Controller

package pers.zhang.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import pers.zhang.entity.Book;
import pers.zhang.service.BookService;

import java.util.List;

/**
 * @author zhang
 * @date 2019/12/18 - 22:25
 */
@Controller
public class BookController {
    @Autowired
    BookService bookService;

    @GetMapping("/findAll")
    public void findAll(){
        PageRequest pageRequest = new PageRequest(2, 3);
        Page<Book> page = bookService.getBooksByPage(pageRequest);
        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(){
        List<Book> bs1 = bookService.getBookByIdAndAuthor("鲁迅", 7);
        List<Book> bs2 = bookService.getBooksByAuthorStartingWith("吴");
        List<Book> bs3 = bookService.getBooksByIdandName("西", 8);
        List<Book> bs4 = bookService.getBooksByPriceGreaterThan(30f);
        Book b = bookService.getMaxIdBook();
        System.out.println("bs1:" + bs1);
        System.out.println("bs2:" + bs2);
        System.out.println("bs3:" + bs3);
        System.out.println("bs4:" + bs4);
        System.out.println("b:" + b);
    }

    @GetMapping("/save")
    public void save(){
        Book book = new Book();
        book.setAuthor("鲁迅");
        book.setName("呐喊");
        book.setPrice(23f);
        bookService.addBook(book);
    }
}

测试

访问前表数据如下
SpringBoot--整合JPA_第1张图片

访问http://localhost:8080/findAll
控制台打印:

Hibernate: select book0_.id as id1_0_, book0_.author as author2_0_, book0_.book_name as book_nam3_0_, book0_.price as price4_0_ from t_book book0_ limit ?, ?
总页数:3
总记录数:7
查询记录:[Book{id=7, name='故事新编', author='鲁迅', price=22.0, description='null'}]
当前页数:3
当前页记录数:1
每页记录数:3

访问http://localhost:8080/save
后台打印:

Hibernate: insert into t_book (author, book_name, price) values (?, ?, ?)

数据表变为:
SpringBoot--整合JPA_第2张图片

访问http://localhost:8080/search
控制台打印:

Hibernate: select book0_.id as id1_0_, book0_.author as author2_0_, book0_.book_name as book_nam3_0_, book0_.price as price4_0_ from t_book book0_ where book0_.id>? and book0_.author=?
Hibernate: select book0_.id as id1_0_, book0_.author as author2_0_, book0_.book_name as book_nam3_0_, book0_.price as price4_0_ from t_book book0_ where book0_.author like ?
Hibernate: select book0_.id as id1_0_, book0_.author as author2_0_, book0_.book_name as book_nam3_0_, book0_.price as price4_0_ from t_book book0_ where book0_.id?
Hibernate: select * from t_book where id = (select max(id) from t_book)
bs1:[Book{id=8, name='呐喊', author='鲁迅', price=23.0, description='null'}]
bs2:[Book{id=3, name='西游记', author='吴承恩', price=29.0, description='null'}]
bs3:[Book{id=3, name='西游记', author='吴承恩', price=29.0, description='null'}]
bs4:[Book{id=2, name='红楼梦', author='曹雪芹', price=35.0, description='null'}, Book{id=5, name='宋词选注', author='钱钟书', price=33.0, description='null'}]
b:Book{id=8, name='呐喊', author='鲁迅', price=23.0, description='null'}

你可能感兴趣的:(Spring,Boot,JPA,SpringBoot,JPA,整合)