Springboot 使用jpa

maven依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-data-jpa</artifactId>
  8. <version>2.2.0.RELEASE</version>
  9. </dependency>
  10. <dependency>
  11. <groupId>mysql</groupId>
  12. <artifactId>mysql-connector-java</artifactId>
  13. <version>8.0.16</version>
  14. </dependency>
  15. <dependency>
  16. <groupId>com.alibaba</groupId>
  17. <artifactId>druid</artifactId>
  18. <version>1.1.20</version>
  19. </dependency>

数据库配置

  1. spring:
  2. datasource:
  3. type: com.alibaba.druid.pool.DruidDataSource
  4. url: jdbc:mysql:///jpa
  5. username: root
  6. password: root
  7. jpa:
  8. show-sql: true
  9. database: mysql
  10. hibernate:
  11. ddl-auto: update

book实体

  1. package com.draymonder.book.jpa;
  2. import javax.persistence.Column;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.GenerationType;
  6. import javax.persistence.Id;
  7. import javax.persistence.Transient;
  8. // 该类是一个实体类, 项目启动时会根据该类自动生成一张表
  9. @Entity
  10. public class Book {
  11. // Id注解表示该属性是一个主键, @GeneratedValue注解表示主键自动生成
  12. @Id
  13. @GeneratedValue(strategy = GenerationType.IDENTITY)
  14. private Integer id;
  15. // Column可以定制属性字段, nullable
  16. @Column(name="book_name", nullable=false)
  17. private String name;
  18. private String author;
  19. private Float price;
  20. // Transient 在生成数据库的表, 该属性被忽略
  21. @Transient
  22. private String desc;
  23. @Override
  24. public String toString() {
  25. return "Book{" +
  26. "id=" + id +
  27. ", name='" + name + '\'' +
  28. ", author='" + author + '\'' +
  29. ", price=" + price +
  30. ", desc='" + desc + '\'' +
  31. '}';
  32. }
  33. public Integer getId() {
  34. return id;
  35. }
  36. public void setId(Integer id) {
  37. this.id = id;
  38. }
  39. public String getName() {
  40. return name;
  41. }
  42. public void setName(String name) {
  43. this.name = name;
  44. }
  45. public String getAuthor() {
  46. return author;
  47. }
  48. public void setAuthor(String author) {
  49. this.author = author;
  50. }
  51. public Float getPrice() {
  52. return price;
  53. }
  54. public void setPrice(Float price) {
  55. this.price = price;
  56. }
  57. public String getDesc() {
  58. return desc;
  59. }
  60. public void setDesc(String desc) {
  61. this.desc = desc;
  62. }
  63. }

bookDao

  1. package com.draymonder.book.jpa;
  2. import java.util.List;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.data.jpa.repository.Query;
  5. import org.springframework.data.repository.query.Param;
  6. public interface BookDao extends JpaRepository<Book, Integer> {
  7. List<Book> getBooksByAuthorStartingWith(String author);
  8. List<Book> getBooksByPriceGreaterThan(Float price);
  9. @Query(value = "select * from book where id=(select max(id) from book)", nativeQuery = true)
  10. Book getMaxIdBook();
  11. @Query("select b from Book b where b.id > :id and b.author = :author")
  12. List<Book> getBookByTry1(@Param("author") String author, @Param("id") Integer id);
  13. @Query("select b from Book b where b.id < ?2 and b.name like %?1%")
  14. List<Book> getBooksByTry(String name, Integer id);
  15. }

bookService

  1. package com.draymonder.book.jpa;
  2. import java.util.List;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.data.domain.Page;
  5. import org.springframework.data.domain.Pageable;
  6. import org.springframework.stereotype.Service;
  7. @Service
  8. public class BookService {
  9. @Autowired
  10. private BookDao bookDao;
  11. public void addBook(Book book) {
  12. bookDao.save(book);
  13. }
  14. public Page<Book> getBookByPage(Pageable pageable) {
  15. return bookDao.findAll(pageable);
  16. }
  17. public List<Book> getBooksByAuthorStartingWith(String author) {
  18. return bookDao.getBooksByAuthorStartingWith(author);
  19. }
  20. public List<Book> getBooksByPriceGreaterThan(Float price) {
  21. return bookDao.getBooksByPriceGreaterThan(price);
  22. }
  23. public Book getMaxIdBook() {
  24. return bookDao.getMaxIdBook();
  25. }
  26. public List<Book> getBookByIdAndAuthor(String author, Integer id) {
  27. return bookDao.getBookByTry1(author, id);
  28. }
  29. public List<Book> getBooksByIdAndName(String name, Integer id) {
  30. return bookDao.getBooksByTry(name, id);
  31. }
  32. }

bookController

  1. package com.draymonder.book.jpa;
  2. import java.util.List;
  3. import javax.websocket.server.PathParam;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.data.domain.Page;
  6. import org.springframework.data.domain.PageRequest;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. import org.springframework.web.bind.annotation.RestController;
  10. @RestController
  11. public class BookController {
  12. @Autowired
  13. BookService bookService;
  14. @GetMapping("/findAll")
  15. public void findAll() {
  16. PageRequest pageable = PageRequest.of(0, 3);
  17. Page<Book> page = bookService.getBookByPage(pageable);
  18. System.out.println("总页数: " + page.getTotalPages());
  19. System.out.println("总记录数: " + page.getTotalElements());
  20. System.out.println("查询结果: " + page.getContent());
  21. System.out.println("当前页数: " + (page.getNumber() + 1));
  22. System.out.println("每页记录数: " + page.getSize());
  23. }
  24. @GetMapping("/search")
  25. public void search() {
  26. List<Book> bs1 = bookService.getBookByIdAndAuthor("鲁迅", 7);
  27. List<Book> bs2 = bookService.getBooksByAuthorStartingWith("吴");
  28. List<Book> bs3 = bookService.getBooksByIdAndName("西", 8);
  29. List<Book> bs4 = bookService.getBooksByPriceGreaterThan(30f);
  30. Book b = bookService.getMaxIdBook();
  31. System.out.println("bs1: " + bs1);
  32. System.out.println("bs2: " + bs2);
  33. System.out.println("bs3: " + bs3);
  34. System.out.println("bs4: " + bs4);
  35. System.out.println("b: " + b);
  36. }
  37. @GetMapping("/save")
  38. public void save(@RequestParam(value="author") String author,
  39. @RequestParam(value="name") String name) {
  40. System.out.println("start");
  41. if (author.isEmpty() || name.isEmpty()) {
  42. return;
  43. }
  44. Book book = new Book();
  45. book.setAuthor(author);
  46. book.setName(name);
  47. book.setPrice(30f);
  48. bookService.addBook(book);
  49. System.out.println("end");
  50. }
  51. }

参考文档

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. (public丶private丶protected) 的理解

    public(公有):公有的类成员可以在任何地方被访问. protected(受保护):受保护的类成员则可以被其自身以及其子类和父类访问. private(私有):私有的类成员则只能被其定义所在的类访 ...

  2. AtCoder Beginner Contest 131 Task F. Must Be Rectangular

    Score: 600 points Approach 固定横坐标 $x$,考虑横坐标为 $x$ 的竖直线上最多可以有几个点. Observations 若最初两条竖直线 $x_1$.$x_2$ 上都有 ...

  3. 小白学习django第五站-简易案例

    首先在setting.py文件中编写数据库配置内容 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': ' ...

  4. Transparency Tutorial with C# - Part 3

    Download image fade demo - 4 Kb Download image fade source project- 7 Kb Download image fade images ...

  5. 大数据学习(1)-shell脚本注意事项

    1.变量=值 (例如STR=abc)  不用加引号,但此时空格不再是空格字符,特殊字符可用于转义 2.等号两侧不能有空格 3.变量名称一般习惯为大写 4.双引号和单引号有区别,双引号仅将空格脱意,单引 ...

  6. centos配置postfix邮件服务

    1.环境初始化 [root@mail ~]# rpm -q centos-release //查看系统版本 centos-release-7-5.1804.el7.centos.x86_64 [roo ...

  7. JS根据一个经纬度及距离角度,算出另外一个经纬度

    var mapNumberUtil = {}; /** * 根据一个经纬度及距离角度,算出另外一个经纬度 * @param {*} lng 经度 113.3960698 * @param {*} la ...

  8. oracle 12C的新特性-CDB和PDB

    1.前言 CDB与PDB是Oracle 12C引入的新特性,在ORACLE 12C数据库引入的多租用户环境(Multitenant Environment)中,允许一个数据库容器(CDB)承载多个可插 ...

  9. python-webdriver中添加cookie,解决添加了图片验证码的问题

    遇到问题:之前一直能用的脚本突然跑不通了,仔细一看原来是研发新加了图片验证码...... 解决问题: 手动抓取了cookie并塞进去,解决问题.当然如果你的cookie有效期太短或者是随着会话关闭就失 ...

  10. Linu目录结构和创建用户

    具体目标结构 ./bin [重点] (/usr/bin./usr/local/bin) ●是Binary的速写,这个目录存放着最经常使用的命令. ./sbin (/usr/sbin./usr/loca ...