当前位置:网站首页>Using the methods in the repository to solve practical problems
Using the methods in the repository to solve practical problems
2022-06-26 11:25:00 【InfoQ】
Repository What are the returned results of

public interface UserRepository extends JpaRepository<User,Long> {
}
User user = userRepository.save(User.builder().name("jackxx").email("[email protected]").sex("man").address("shanghai").build());
Assert.assertNotNull(user);
Streamable<User> userStreamable = userRepository.findAll(PageRequest.of(0,10)).and(User.builder().name("jack222").build());
userStreamable.forEach(System.out::println);
User(id=1, name=jackxx, [email protected], sex=man, address=shanghai)
User(id=null, name=jack222, email=null, sex=null, address=null)
<User>Customize Streamable
class Product { (1)
MonetaryAmount getPrice() { … }
}
@RequiredArgConstructor(staticName = "of")
class Products implements Streamable<Product> { (2)
private Streamable<Product> streamable;
public MonetaryAmount getTotal() { (3)
return streamable.stream() //
.map(Priced::getPrice)
.reduce(Money.of(0), MonetaryAmount::add);
}
}
interface ProductRepository implements Repository<Product, Long> {
Products findAllByDescriptionContaining(String text); (4)
}
<Product><Product><Product>
Return result type List/Stream/Page/Slice
package com.example.jpa.example1;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.stream.Stream;
public interface UserRepository extends JpaRepository<User,Long> {
// Customize a query method , return Stream object , And has paging properties
@Query("select u from User u")
Stream<User> findAllByCustomQueryAndStream(Pageable pageable);
// test Slice Return result of
@Query("select u from User u")
Slice<User> findAllByCustomQueryAndSlice(Pageable pageable);
}
package com.example.jpa.example1;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.assertj.core.util.Lists;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Slice;
import org.springframework.data.util.Streamable;
import java.util.List;
import java.util.stream.Stream;
@DataJpaTest
public class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Test
public void testSaveUser() throws JsonProcessingException {
// We added 7 This piece of data is convenient for testing paging results
userRepository.save(User.builder().name("jack1").email("[email protected]").sex("man").address("shanghai").build());
userRepository.save(User.builder().name("jack2").email("[email protected]").sex("man").address("shanghai").build());
userRepository.save(User.builder().name("jack3").email("[email protected]").sex("man").address("shanghai").build());
userRepository.save(User.builder().name("jack4").email("[email protected]").sex("man").address("shanghai").build());
userRepository.save(User.builder().name("jack5").email("[email protected]").sex("man").address("shanghai").build());
userRepository.save(User.builder().name("jack6").email("[email protected]").sex("man").address("shanghai").build());
userRepository.save(User.builder().name("jack7").email("[email protected]").sex("man").address("shanghai").build());
// We make use of ObjectMapper Return our results Json to String
ObjectMapper objectMapper = new ObjectMapper();
// return Stream Type the results (1)
Stream<User> userStream = userRepository.findAllByCustomQueryAndStream(PageRequest.of(1,3));
userStream.forEach(System.out::println);
// Return paging data (2)
Page<User> userPage = userRepository.findAll(PageRequest.of(0,3));
System.out.println(objectMapper.writeValueAsString(userPage));
// return Slice result (3)
Slice<User> userSlice = userRepository.findAllByCustomQueryAndSlice(PageRequest.of(0,3));
System.out.println(objectMapper.writeValueAsString(userSlice));
// return List result (4)
List<User> userList = userRepository.findAllById(Lists.newArrayList(1L,2L));
System.out.println(objectMapper.writeValueAsString(userList));
}
}
<User>Stream<User> stream;
try {
stream = repository.findAllByCustomQueryAndStream()
stream.forEach(…);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream!=null){
stream.close();
}
}
<User>{
"content":[
{
"id":1,
"name":"jack1",
"email":"[email protected]",
"sex":"man",
"address":"shanghai"
},
{
"id":2,
"name":"jack2",
"email":"[email protected]",
"sex":"man",
"address":"shanghai"
},
{
"id":3,
"name":"jack3",
"email":"[email protected]",
"sex":"man",
"address":"shanghai"
}
],
"pageable":{
"sort":{
"sorted":false,
"unsorted":true,
"empty":true
},
"pageNumber":0, The current page number
"pageSize":3, Page size
"offset":0, Offset
"paged":true, Whether it is paged
"unpaged":false
},
"totalPages":3, How many pages are there in all
"last":false, Whether it is in the end
"totalElements":7, How many keys are there
"numberOfElements":3, Current data subscript
"sort":{
"sorted":false,
"unsorted":true,
"empty":true
},
"size":3, At present content size
"number":0, Index of the current page code
"first":true, Is it the first page
"empty":false Is there any data
}
<User>- content: Content of data , Now refers to User Of List 3 strip .
- pageable: Paging data , Including what sort field is and its direction 、 What page is it now 、 How many pages altogether 、 Is it the last one .
- Description of the current data:“size”:3, At present content size ;“number”:0, Index of the current page code ; “first”:true, Is it the first page ;“empty”:false, Whether there is no data .
<User>{
"content":[
{
"id":4,
"name":"jack4",
"email":"[email protected]",
"sex":"man",
"address":"shanghai"
},
{
"id":5,
"name":"jack5",
"email":"[email protected]",
"sex":"man",
"address":"shanghai"
},
{
"id":6,
"name":"jack6",
"email":"[email protected]",
"sex":"man",
"address":"shanghai"
}
],
"pageable":{
"sort":{
"sorted":false,
"unsorted":true,
"empty":true
},
"pageNumber":1,
"pageSize":3,
"offset":3,
"paged":true,
"unpaged":false
},
"numberOfElements":3,
"sort":{
"sorted":false,
"unsorted":true,
"empty":true
},
"size":3,
"number":1,
"first":false,
"last":false,
"empty":false
}
Query paging data
Hibernate: select user0_.id as id1_0_, user0_.address as address2_0_, user0_.email as email3_0_, user0_.name as name4_0_, user0_.sex as sex5_0_ from user user0_ limit ?
Calculate paging data
Hibernate: select count(user0_.id) as col_0_0_ from user user0_
Hibernate: select user0_.id as id1_0_, user0_.address as address2_0_, user0_.email as email3_0_, user0_.name as name4_0_, user0_.sex as sex5_0_ from user user0_ limit ? offset ?
<User>[
{
"id":1,
"name":"jack1",
"email":"[email protected]",
"sex":"man",
"address":"shanghai"
},
{
"id":2,
"name":"jack2",
"email":"[email protected]",
"sex":"man",
"address":"shanghai"
}
]
Repository Yes Feature/CompletableFuture Support for asynchronously returning results :
@Async
Future<User> findByFirstname(String firstname); (1)
@Async
CompletableFuture<User> findOneByFirstname(String firstname); (2)
@Async
ListenableFuture<User> findOneByLastname(String lastname);(3)
- First of all : Use java.util.concurrent.Future The return type of ;
- The second place : Use java.util.concurrent.CompletableFuture As return type ;
- The third place : Use org.springframework.util.concurrent.ListenableFuture As return type .
- In practice , Directly in Repository There are few scenarios in which asynchronous methods are used in this layer , Generally, asynchronous annotations are placed in Service The method above , In this case , There can be some additional logic , If you send a text message 、 email 、 Send messages, etc ;
- When using asynchrony, you must configure the thread pool , Remember this , otherwise “ die ” It will be ugly .
边栏推荐
- (Typora图床)阿里云oss搭建图床+Picgo上传图片详细教程
- 我想知道同花顺是炒股的么?手机开户安全么?
- Is it safe to open a stock account by mobile phone
- Matlab programming example: how to count the number of elements in a cell array
- laravel-admin隐藏按钮, 及设置按钮显示, 默认序列, form 表单的不可修改值
- CEPH operation and maintenance common instructions
- [deep learning theory] (6) recurrent neural network RNN
- Nacos2.x.x start error creating bean with name 'grpcclusterserver';
- Redis的最佳实践?看完不心动,算我输!!
- How to calculate flops and params in deep learning
猜你喜欢

(Typora图床)阿里云oss搭建图床+Picgo上传图片详细教程

量化初级 -- akshare获得股票代码,最简策略

机器学习PCA——实验报告

深度学习中的FLOPs和Params如何计算

SVN 安装配置

redux相关用法

19:第三章:开发通行证服务:2:在程序中,打通阿里云短信服务;(仅仅是打通阿里云短信服务器,不涉及具体的业务开发)

That is to say, "live broadcast" is launched! One stop live broadcast service with full link upgrade
![LeetCode 710 黑名单中的随机数[随机数] HERODING的LeetCode之路](/img/58/2a56c5c9165295c830082f8b05dd98.png)
LeetCode 710 黑名单中的随机数[随机数] HERODING的LeetCode之路

Machine learning SVM - Experimental Report
随机推荐
FastRCNN
Origin of b+ tree index
laravel-admin隐藏按钮, 及设置按钮显示, 默认序列, form 表单的不可修改值
Solidworks渲染技巧如何不显示边线--显示样式设定
Fabric. JS upper dash, middle dash (strikethrough), underline
【深度学习理论】(6) 循环神经网络 RNN
Build document editor based on slate
SolidWorks rendering tips how not to display edges -- display style settings
PC QQ大廳 上傳更新 修改versionInfo
Redis的最佳实践?看完不心动,算我输!!
深度理解STM32的串口实验(寄存器)【保姆级教程】
PC qq Hall upload Update Modifying versioninfo
laravel-admin 用 原生JS实现声音提示,及自动播放
修改calico网络模式为host-gw
Detailed explanation of MySQL fuzzy query
Redis best practices? If I don't feel excited after reading it, I will lose!!
【深度学习理论】(7) 长短时记忆网络 LSTM
word中涂黑的方块
Excel operation of manual moving average method and exponential smoothing method for time series prediction
Mqtt disconnect and reconnect