标签:关联 throws view err ESS png 查询 public add
主要适用于需要查询多种类型的数据,而且二者的参数没有关联的情况。
1、开启异步调用注解
2、创建抽象类,定义相关方法
1 /** 2 * @author:YZH 3 * time: 2019/8/8 12:16 4 * description: 建立抽象类,定义相关方法 5 **/ 6 public abstract class BaseAdapt<T,Base>{ 7 private Base base; 8 9 public BaseAdapt(Base base){ 10 this.base = base; 11 } 12 13 /** 14 * 查询list数据(默认要实现) 15 * @return 16 */ 17 public abstract List<T>list(); 18 19 /** 20 * 查询数量 21 * @return 22 */ 23 public int count(){return 0;} 24 25 /** 26 * 返回单个对象V 27 * @return 28 */ 29 public T getT(){ 30 return null; 31 } 32 33 }
3、建立异步调用方法
1 @Component 2 public class DemoThread { 3 4 5 @Async 6 public <T,Base> Future<T> getT(BaseAdapt<T,Base>baseAdapt) { 7 return new AsyncResult<>(baseAdapt.getT()); 8 } 9 10 @Async 11 public <T,Base> Future<List<T>> list(BaseAdapt<T,Base> baseAdapt){ 12 return new AsyncResult<>(baseAdapt.list()); 13 } 14 15 @Async 16 public Future<Integer>count(BaseAdapt baseAdapt){ 17 return new AsyncResult<>(baseAdapt.count()); 18 } 19 }
4、建立一个dao类,模拟访问数据库
1 @Component 2 public class UserDao { 3 4 public User getUser(){ 5 User user = new User(); 6 user.setName("测试"); 7 user.setId(UUID.randomUUID().toString()); 8 return user; 9 } 10 11 public List<User>listUser(){ 12 int num = new Random(1).nextInt(10); 13 System.out.println("随机生成:"+num+"个user"); 14 List<User>users = new ArrayList<>(num); 15 for (int i = 0; i < num; i++) { 16 User user = new User(); 17 user.setId(UUID.randomUUID().toString()); 18 user.setName("测试"+i); 19 users.add(user); 20 } 21 return users; 22 } 23 public int count(){ 24 return new Random(1).nextInt(10); 25 } 26 }
5、调用
a、只实现默认方法,获取list数据
1 @Test 2 public void testAsync() throws InstantiationException, IllegalAccessException, ExecutionException, InterruptedException { 3 BaseAdapt<User,UserDao>baseAdapt = new BaseAdapt<User, UserDao>(userDao) { 4 @Override 5 public List<User> list() { 6 return userDao.listUser(); 7 } 8 }; 9 Future<List<User>> list = demoThread.list(baseAdapt); 10 Future<Integer> count = demoThread.count(baseAdapt); 11 List<User> users = list.get(); 12 Integer integer = count.get(); 13 System.out.println("总数:"+integer); 14 for (User user : users) { 15 System.out.println(user); 16 } 17 }
b、新增查询数量
1 @Test 2 public void testAsync() throws InstantiationException, IllegalAccessException, ExecutionException, InterruptedException { 3 BaseAdapt<User,UserDao>baseAdapt = new BaseAdapt<User, UserDao>(userDao) { 4 @Override 5 public List<User> list() { 6 return userDao.listUser(); 7 } 8 @Override 9 public int count() { 10 return userDao.count(); 11 } 12 }; 13 Future<List<User>> list = demoThread.list(baseAdapt); 14 Future<Integer> count = demoThread.count(baseAdapt); 15 List<User> users = list.get(); 16 Integer integer = count.get(); 17 System.out.println("总数:"+integer); 18 for (User user : users) { 19 System.out.println(user); 20 } 21 }
标签:关联 throws view err ESS png 查询 public add
原文地址:https://www.cnblogs.com/cq-yangzhou/p/11325520.html