<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
JPA (Java Persistence API)和 Spring Data 是兩個範疇的概念。
Hibernate 是一個 ORM 框架,JPA 則是一種ORM,JPA 和 Hibernate 的關係就像 JDBC 與 JDBC 驅動,即 JPA 制定了 ORM 規範,而 Hibernate 是這些規範的實現(事實上,是現有 Hibernate 後有 JPA ,JPA 規範的起草也是 Hibernate 的作者),因此從功能上來說,JPA 相當於 Hibernate 的一個子集。
Spring Data 是 Spring 的一個子專案,致力於簡化資料庫存取,通過規範的方法名稱來分析開發者的意圖,進而減少資料庫存取層的程式碼量。Spring Data 不僅支援關係型資料庫,也支援非關係型資料庫。Spring Data JPA 可以有效簡化關係型資料庫存取程式碼。
Spring Boot 整合 Spring Data JPA 步驟如下:
建立資料庫即可,不用建立表
建立資料庫 jpa,如下
create database `jpa` default character set utf8;
建立 Spring Boot 專案,新增 MySQL 和 Spring Data JPA 的依賴
<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>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
在 application.properties 中設定資料庫基本資訊以及 JPA 相關設定
# 資料庫基本設定
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
# JPA 設定
spring.jpa.show-sql=true
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
@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; @Override public String toString() { return "Book{" + "id=" + id + ", name='" + name + ''' + ", author='" + author + ''' + ", price=" + price + ", description='" + description + ''' + '}'; } public String getDescription() { return description; } public void setDescription(String description) { this.description = 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 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("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); }
程式碼解釋:
| 關鍵字 | 方法命名 | sql where字句 |
| — | — | — |
| And | findByNameAndPwd | where name= ? and pwd =? |
| Or | findByNameOrSex | where name= ? or sex=? |
| Is,Equals | findById,findByIdEquals | where id= ? |
| Between | findByIdBetween | where id between ? and ? |
| LessThan | findByIdLessThan | where id < ? |
| LessThanEqual | findByIdLessThanEqual | where id <= ? |
| GreaterThan | findByIdGreaterThan | where id > ? |
| GreaterThanEqual | findByIdGreaterThanEqual | where id > = ? |
| After | findByIdAfter | where id > ? |
| Before | findByIdBefore | where id < ? |
| IsNull | findByNameIsNull | where name is null |
| isNotNull,NotNull | findByNameNotNull | where name is not null |
| Like | findByNameLike | where name like ? |
| NotLike | findByNameNotLike | where name not like ? |
| StartingWith | findByNameStartingWith | where name like ‘?%’ |
| EndingWith | findByNameEndingWith | where name like ‘%?’ |
| Containing | findByNameContaining | where name like ‘%?%’ |
| OrderBy | findByIdOrderByXDesc | where id=? order by x desc |
| Not | findByNameNot | where name <> ? |
| In | findByIdIn(Collection<?> c) | where id in (?) | | NotIn | findByIdNotIn(Collection<?> c) | where id not in (?) |
| True | findByAaaTue | where aaa = true |
| False | findByAaaFalse | where aaa = false |
| IgnoreCase | findByNameIgnoreCase | where UPPER(name)=UPPER(?) |
@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.getBooksByIdAndName(name, id); } }
程式碼解釋:
@RestController public class BookController { @Autowired BookService bookService; @GetMapping("/findAll") public void findAll() { PageRequest 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() { 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); } }
程式碼解釋:
啟動專案,檢視資料庫發現 t_book 表已自動新建,新增測試資料
INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (1, '羅貫中', '三國演義', 30); INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (2, '曹雪芹', '紅樓夢', 35); INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (3, '吳承恩', '西遊記', 29); INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (4, '施耐庵', '水滸傳', 29); INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (5, '錢鍾書', '宋詩選注', 33); INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (6, '魯迅', '朝花夕拾', 18); INSERT INTO `jpa`.`t_book`(`id`, `author`, `book_name`, `price`) VALUES (7, '魯迅', '故事新編', 22);
然後呼叫 /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
接著呼叫 /save 介面 ,檢視資料庫表資料,如下
最後呼叫 /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 ? escape ?
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_.book_name 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_.price>?
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 整合持久層之Spring Data JPA的文章就介紹到這了,更多相關Spring Boot Spring Data JPA內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45