org.jooq.impl.DSL是生成所有jooq对象的主要类。作为一个静态的工厂去生成数据库表表达式、列表达式、条件表达式和其它查询部分。使用dsl时,导入org.jooq.impl.DSL.*
DSLContext和DSL 是访问JOOQ类和功能的主要入口点。
如:
创建一个常量值的字段,
Field
Condition condition = DSL.exists(DSL.select(DSL.field("username")));等价于select * from 表 where exists (select username from dual);
获取表记录对象:
Table
根据数据库连接生成操作数据库的对象
DSLContext dsl = DSL.using(connection);
DSLContext引用了org.jooq.Configuration。。。Configuration配置了jooq的行为
小例子:
案例:我想关联查询TB_ELECOCOC和TB_ELECOCO_DAPARTMENT,两个表通过appid关联,,我想查询TB_ELECOCOC中RESULTSTRING为""的,TB_ELECOCO_DAPARTMENT中的MODULEOWNER字段。。。还有要去重
对应的sql语句可以为:
select DISTINCT d.moduleowner
from tb_elecoco e
left join tb_elecoco_dapartment d on e.appid = d.appid
where e.resultstring = "";
where e.appid = d.appid and e.resultstring = "";
我们用join。。。。
1、创建DO,虽然里面只有一个字段但是我还是创建了一个do用来匹配查询结果:
package me.ele.xxx.xxx.xxx; public class QueryElecocoOwnerEmailDo { //private String appId; private String moduleOwner; public String getModuleOwner() { return moduleOwner; } public void setModuleOwner(String moduleOwner) { this.moduleOwner = moduleOwner; } @Override public String toString() { return "QueryElecocoOwnerEmailDo{" + "moduleOwner='" + moduleOwner + '\'' + '}'; } }
2、创建查询类,类中需要有数据库相关的信息,如,数据库url,username,password
package me.ele.xxx.xxx.xx; import org.jooq.*; import org.jooq.impl.DSL; import java.sql.Connection; import java.sql.DriverManager; import java.util.List; import static xxxx.xxx.xxx.TB_ELECOCO;//这块倒入的就是jooq根据数据库自动生成的那些class import static xxx.xxx.xxx..TB_ELECOCO_DAPARTMENT; public class QueryElecocoOwnerEmail { private static String driver="com.mysql.jdbc.Driver"; private static String url="jdbc:mysql://127.0.0.1:3306/数据名"; private static String username="用户名"; private static String password="密码"; private static Connection ct=null; private static DSLContext dslContext=null; static { try { Class.forName(driver); ct=DriverManager.getConnection(url, username, password); dslContext=DSL.using(ct); } catch (Exception e) { e.printStackTrace(); } }
//查询方法getElecocoOwnerEmail(String 条件)。。 }
3、完善查询方法:
public ListgetElecocoOwnerEmail(String resultString) { List moduleOwners = dslContext.selectDistinct(TB_ELECOCO_DAPARTMENT.MODULEOWNER.as("moduleOwner")) .from(TB_ELECOCO_DAPARTMENT) .leftJoin(TB_ELECOCO) .on(TB_ELECOCO_DAPARTMENT.APPID.eq(TB_ELECOCO.APPID)) .where(TB_ELECOCO.RESULTSTRING.eq(resultString)) .fetchInto(QueryElecocoOwnerEmailDo.class); for(QueryElecocoOwnerEmailDo queryElecocoOwnerEmailDo : moduleOwners){ String moduleOwner = queryElecocoOwnerEmailDo.getModuleOwner(); if(moduleOwner.equals("xxx")){ System.out.println("===="); } } return moduleOwners; } public static void main(String[] args){ QueryElecocoOwnerEmail q = new QueryElecocoOwnerEmail(); q.getElecocoOwnerEmail(""); }