《ThinkJDBC—一行代码搞定数据库操作》 项目地址 https://gitee.com/Leytton/ThinkJD
0x01 链式调用
首先我们来实现链式调用方法,所谓链式调用就是一行代码能多次调用对象方法,类似语法格式为
new M().table("user").field("id,name").where("id=3").find();
ThinkJD的主要数据库逻辑是在M类里实现的,首先建立M.java
类,并添加构造方法M()
、M(String table)
,和两个普通方法field()
、where()
分别用于给field、where属性赋值。
public class M {
private String table;
private String field;
private String where;
public M(){
}
public M(String table){
this.table=table;
}
public void field(String filed) {
this.field = filed;
}
public void where(String where) {
this.where = "where " + where;
}
}
此时M m=new M("user");
返回的是一个table属性值为user
的对象实例m
。给field
属性赋值,m.field("id,name");
,再给where
属性赋值m.where("id=3");
此处用了3行代码才完成。
那么改成下面代码
public class M {
...
public M field(String filed) {
this.field = filed;
return this;
}
public M where(String where) {
this.where = "where " + where;
return this;
}
}
与上面代码不同的是field()
和where()
方法都添加了返回语句return this;
返回的是M实例对象本身。new M("user")
返回的是实例对象假设为m
,m
调用field()
方法:new M("user").field("id,name")
返回的还是对象m
!!! m
再调用where()
方法:new M("user").field("id,name").where("id=3")
返回的依旧是对象m
!!!这样就可以多次连续甚至重复调用m
里的方法了。
在此,我们实现了M类里的链式调用方法。
链式调用方法还经常用于javaBean对象。如new User().setId(123).setName(“Leytton”)
0x02 D.M()方法实现
每次创建M类对象都要 new M()
,ThinkJD提供了更快的调用方式D.M()
。
查看源码
public class D {
...
public static M M() throws SQLException {
return new M();
}
public static M M(String table) throws SQLException {
return new M(table);
}
}
D类的M()和M(String table)是静态方法,不需要new出一个实例对象就可以调用D.M()
,返回的是M类实例对象。