公司作项目,都是使用Mybatis, 我的不太喜欢xml的方式,天然也尝试无xml的Mybatis,在以前写的一篇多数据源+Mybatis+无xml配置.html
不废话,本篇记录使用JPA遇到的问题笔记.java
写到Dao层,继承JpaRepository,实现分页时候的问题.spring
public interface HelloRepository extends JpaRepository<Hello,Integer>
单元测试的时候,用到了PageRequestapi
PageRequest pageRequest=newPageRequest(0,10);
这明显是过时了,不能容忍的强迫症犯发,点进去API查看安全
发现3个构造器都@Deprecated注解,说明过期的调用方式,不推荐使用.dom
再往下看,能够找到static的方法,是用来建造PageRequest对象的,内部调用的也是原来的构造器.函数
把原来的 new PageRequest 改为 PageRequest.of(0,10);单元测试
有3个重载 对应 3个构造器.学习
官方API说明: since 2.0, use of(...)
instead.测试
2.0版本后,使用 of(...) 方法代替 PageRequest(...)构造器
URL : ↓↓↓
https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/PageRequest.html
扩展学习一下API的设计思想
分析: PageRequest构造器中的参数最可能是4个参数,其中必填的是2个参数(page,rows)
另外2个参数是选填direction(正序倒序),properties(排序字段)
设计这该类的构造器的方法有几种方案:
1.重叠构造器模式
2.JavaBeans模式
3.构建器模式
其余.......
构建结构 : 由参数少的构造器向参数多的构造器方向调用, 最终调用参数多的构造器建立对象.
好处: 只要有必要参数,就能够建立对象; 若是还知道了选填的控制参数,就能够选择性的建立可控的对象
坏处: 若是参数多了,就是一大坨,一坨接一坨,闪闪发光
public class LotShit { private Double wight; private String color; private String whoS; private boolean sweet; public LotShit(Double wight) { this(wight,"golden"); } public LotShit(Double wight, String color) { this(wight,color,"大黄"); } public LotShit(Double wight, String color,String whoS) { this(wight,color,whoS,true); } public LotShit(Double wight, String color, String whoS, boolean sweet) { this.wight = wight; this.color = color; this.whoS = whoS; this.sweet = sweet; } }
构建结构 : 遵循特定规则的java类,必须有一个无参的构造函数、属性必须私有化private、私有化的属性必须经过公有类型的方法(get/set)对外暴露
好处 : 建立简单,想要什么本身加什么
坏处 : 构造过程能够被set改变字段值,不能保证其安全
public class LotShit { private Double wight; private String color; private String whoS; private boolean sweet; public LotShit(){} //getter & setter ... }
构建结构 : 一个复杂对象的构建和表示分离,使得一样的构建过程能够创造建立不一样的表示
好处 : 能够灵活构造复杂对象实例,适用于多个构造器参数,且参数包含必选和可选参数
坏处 : 写起来复杂了,构建实例成本高了
只有2个参数,仍是不要用了,若是你不是闲得慌的话
public class LotShit { private Double wight; private String color; private String whoS; private boolean sweet; private LotShit(Shit shit) { this.wight=shit.wight; this.color=shit.color; this.whoS=shit.whoS; this.sweet=shit.sweet; } public static class Shit { private Double wight; private String color; private String whoS; private boolean sweet; public LotShit create() { return new LotShit(this); } private Shit setWight(Double wight) { this.wight = wight; return this; } private Shit setColor(String color) { this.color = color; return this; } private Shit setSweet(boolean sweet) { this.sweet = sweet; return this; } private Shit setWhoS(String whoS) { this.whoS = whoS; return this; } } }
说了这么多,彷佛PageRequest用的静态方法代替构造器的方式和上面没有什么关系,哈哈哈
这里区别于工厂方法模式中的,它只是一个静态的方法,工厂方法模式一般有产品和工厂两部分
这样使用的分析一下:
1. 能够自定义方法名字,区别多个构造器是干什么用的,构建的阶段什么的,明显PageRequest.of用的都同样,统一与构造器结构也不错,哈哈哈
2. 能够充分利用多态,使代码更具备可扩展性,好比返回子类的实例,构造器则不行
3. 同样具备重叠构造器的优势
4. 若是该类中没有public或protected的构造器,该类就不能使用静态方法子类化
5.基于第4点,策略模式说到应该多用组合而不是继承,当一个类不能子类化后,组合将是你惟一的选择
PS: 静态工厂方法本质上就是一个静态方法
---------------------------------------------------------------