Springboot 使用JPA

Springboot 使用jpa

maven依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
  <version>2.2.0.RELEASE</version>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.16</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.1.20</version>
</dependency>

数据库配置

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql:///jpa
    username: root
    password: root
  jpa:
    show-sql: true
    database: mysql
    hibernate:
      ddl-auto: update

book实体

package com.draymonder.book.jpa;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Transient;

// 该类是一个实体类, 项目启动时会根据该类自动生成一张表
@Entity
public class Book {
  // Id注解表示该属性是一个主键, @GeneratedValue注解表示主键自动生成
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  // Column可以定制属性字段, nullable
  @Column(name="book_name", nullable=false)
  private String name;

  private String author;

  private Float price;

  // Transient 在生成数据库的表, 该属性被忽略
  @Transient
  private String desc;

  @Override
  public String toString() {
    return "Book{" +
        "id=" + id +
        ", name='" + name + '\'' +
        ", author='" + author + '\'' +
        ", price=" + price +
        ", desc='" + desc + '\'' +
        '}';
  }

  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 getDesc() {
    return desc;
  }

  public void setDesc(String desc) {
    this.desc = desc;
  }
}

bookDao

package com.draymonder.book.jpa;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface BookDao extends JpaRepository<Book, Integer> {

  List<Book> getBooksByAuthorStartingWith(String author);

  List<Book> getBooksByPriceGreaterThan(Float price);

  @Query(value = "select * from book where id=(select max(id) from book)", nativeQuery = true)
  Book getMaxIdBook();

  @Query("select b from Book b where b.id > :id and b.author = :author")
  List<Book> getBookByTry1(@Param("author") String author, @Param("id") Integer id);

  @Query("select b from Book b where b.id < ?2 and b.name like %?1%")
  List<Book> getBooksByTry(String name, Integer id);
}

bookService

package com.draymonder.book.jpa;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class BookService {
  @Autowired
  private 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.getBookByTry1(author, id);
  }

  public List<Book> getBooksByIdAndName(String name, Integer id) {
    return bookDao.getBooksByTry(name, id);
  }

}

bookController

package com.draymonder.book.jpa;

import java.util.List;
import javax.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BookController {

  @Autowired
  BookService bookService;

  @GetMapping("/findAll")
  public void findAll() {
    PageRequest pageable = PageRequest.of(0, 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.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(@RequestParam(value="author") String author,
        @RequestParam(value="name") String name) {
    System.out.println("start");
    if (author.isEmpty() || name.isEmpty()) {
      return;
    }
    Book book = new Book();
    book.setAuthor(author);
    book.setName(name);
    book.setPrice(30f);
    bookService.addBook(book);
    System.out.println("end");
  }
}

参考文档

JPQL: jianshu.com/p/4a4410075bab

原文地址:https://www.cnblogs.com/Draymonder/p/11827293.html

时间: 2024-10-08 14:29:55

Springboot 使用JPA的相关文章

springboot使用jpa,删除功能sql报错解决

springboot使用jpa时报错: 只有删除时报错了, "data": "删除失败,原因:Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failur

二、springboot使用jpa

花了几天时间,好好看了看springboot的jpa部分,总结了常用的形式. 1.通过STS工具添加jpa的依赖项 要连mysql,测试的时候需要web,顺便添加了lombok不写set和get方法了. 2.添加配置 application.properties: 要连接mysql.设置jpa的两个参数,一个是更改entity后更新表,还一个是显示sql,为了查错用 添加一个config类,开启jpa,添加扫描repository路径 最后需要建立一个web请求入口,方便调用调试,增加web很简

带你搭一个SpringBoot+SpringData JPA的环境

前言 只有光头才能变强. 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 不知道大家对SpringBoot和Spring Data JPA了解多少,如果你已经学过Spring和Hibernate的话,那么SpringBoot和SpringData JPA可以分分钟上手的.SpringBoot和SpringData JPA的好处我就不说了,当时我学习的时候也粗略做过笔记,有兴趣的同学可以去看看 SpringBoot就是这么简

【极简版】SpringBoot+SpringData JPA 管理系统

前言 只有光头才能变强. 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 在上一篇中已经讲解了如何从零搭建一个SpringBoot+SpringData JPA的环境,测试接口的时候也成功获取得到数据了. 带你搭一个SpringBoot+SpringData JPA的Demo 我的目的是做一个十分简易的管理系统,这就得有页面,下面我继续来讲讲我是怎么快速搭一个管理系统的. ps:由于是简易版,我的目的是能够快速搭建,而不在

用SpringBoot+MySql+JPA实现对数据库的增删改查和分页

使用SpringBoot+Mysql+JPA实现对数据库的增删改查和分页      JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中.  使用Springboot和jpa对数据库进行操作时,能够大大减少我们的工作量,在jpa中,已经在底层封装好了增删查的功能和sql语句,可以使我们进行快速开发 项目流程 一.新建一个项目 二.配置文件 #数据源配置 spring.dat

springboot之jpa的支持

1.springboot之jpa支持 2.Springboot+bootstrap界面版之增删改查及图片上传 springboot之jpa支持 导入相关pom依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> application.

springboot对JPA的支持

目标 1.springboot之jpa支持 2.Springboot+bootstrap界面版之增删改查及图片上传 spring boot之jpa支持 导入pom依赖 1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-data-jpa</artifactId> 4 </dependency> 配置

【SpringBoot】SpringBoot 与JPA整合(十四)

本章介绍SpringBoot与JPA整合 整合流程 1.新建一个SpringBoot Web项目 1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:s

springboot使用jpa+mongodb时,xxxRepository不能Autowired的问题

springboot启动类: @SpringBootApplication public class MainApp { public static void main(String[] args) { SpringApplication.run(MainApp.class, args); } } jpa数据库操作类: public interface UserDao extends MongoRepository<User, String> { } 单元测试类: @RunWith(Sprin