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

jpa补充: http://www.ityouknow.com/springboot/2016/08/20/spring-boot-jpa.html

Springboot 使用JPA的更多相关文章

  1. Springboot+Atomikos+Jpa+Mysql实现JTA分布式事务

    1 前言 之前整理了一个spring+jotm实现的分布式事务实现,但是听说spring3.X后不再支持jotm了,jotm也有好几年没更新了,所以今天整理springboot+Atomikos+jp ...

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

    前言 只有光头才能变强. 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 在上一篇中已经讲解了如何从零搭建一个SpringBo ...

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

    前言 只有光头才能变强. 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 不知道大家对SpringBoot和Spring Da ...

  4. 二、springboot使用jpa

    花了几天时间,好好看了看springboot的jpa部分,总结了常用的形式. 1.通过STS工具添加jpa的依赖项 要连mysql,测试的时候需要web,顺便添加了lombok不写set和get方法了 ...

  5. Springboot+MyBatis+JPA集成

      1.前言 Springboot最近可谓是非常的火,本人也在项目中尝到了甜头.之前一直使用Springboot+JPA,用了一段时间发现JPA不是太灵活,也有可能是我不精通JPA,总之为了多学学Sp ...

  6. 第11章—使用对象关系映射持久化数据—SpringBoot+SpringData+Jpa进行查询修改数据库

    SpringBoot+SpringData+Jpa进行查询修改数据库 JPA由EJB 3.0软件专家组开发,作为JSR-220实现的一部分.但它又不限于EJB 3.0,你可以在Web应用.甚至桌面应用 ...

  7. 集成Springboot+MyBatis+JPA

    1.前言 Springboot最近可谓是非常的火,本人也在项目中尝到了甜头.之前一直使用Springboot+JPA,用了一段时间发现JPA不是太灵活,也有可能是我不精通JPA,总之为了多学学Spri ...

  8. SpringBoot Data JPA 关联表查询的方法

    SpringBoot Data JPA实现 一对多.多对一关联表查询 开发环境 IDEA 2017.1 Java1.8 SpringBoot 2.0 MySQL 5.X 功能需求 通过关联关系查询商店 ...

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

    使用SpringBoot+Mysql+JPA实现对数据库的增删改查和分页      JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述 ...

  10. springboot使用Jpa连接数据库

    springboot使用Jpa连接数据库 1.pom.xml: <?xml version="1.0" encoding="UTF-8"?> < ...

随机推荐

  1. Python学习【day02】- Python基础练习题

    #!/usr/bin/env python # -*- coding:utf8 -*- # 执行Python 脚本的两种方式 # 答:①在windows的cmd窗口下 > D:/Python/p ...

  2. L2-014. 列车调度(Dilworth定理)

    火车站的列车调度铁轨的结构如下图所示. Figure 两端分别是一条入口(Entrance)轨道和一条出口(Exit)轨道,它们之间有N条平行的轨道.每趟列车从入口可以选择任意一条轨道进入,最后从出口 ...

  3. Postman之获得登录的token,并设置为全局变量

    1.调通登录接口(可以参考上篇博客) 网址:Postman之简单使用 2.粘贴以下代码到Tests中 //把json字符串转化为对象 var data=JSON.parse(responseBody) ...

  4. k8s 1.9安装

    关闭所有节点的selinux.iptables.firewalld systemctl stop iptables systemctl stop firewalld systemctl disable ...

  5. Docker 镜像与容器管理

    镜像与容器简介 Docker的大部分操作都围绕着它的三大核心概念:镜像.容器.仓库而展开.因此,准确把握这三大核心概念对于掌握Docker技术尤为重要,在docker中,我们重点关注的就是镜像和容器了 ...

  6. CF 403D Beautiful Pairs of Numbers

    The sequence of integer pairs (a1, b1), (a2, b2), ..., (ak, bk) is beautiful, if the following state ...

  7. intelij IDEA设置goole code style风格

    1.安装google-java-format 插件      file ->Setings... ->pligins     输入上诉插件安装 2.下载IntelliJ Java Goog ...

  8. Python 并发网络库

    Python 并发网络库 Tornado VS Gevent VS Asyncio Tornado:并发网络库,同时也是一个 web 微框架 Gevent:绿色线程(greenlet)实现并发,猴子补 ...

  9. ASP.NET CORE CACHE的使用(含MemoryCache,Redis)

    原文:ASP.NET CORE CACHE的使用(含MemoryCache,Redis) 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接 ...

  10. 第四篇 jQuery中的事件与应用

    4.1 事件中的冒泡现象,ready()方法 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" & ...