复杂查询

QuickDAO提供了丰富的单表查询操作.

Person实体类

  1. public class Person {
  2. @Id(strategy = IdStrategy.AutoIncrement)
  3. private long id;
  4. private String username;
  5. private String password;
  6. private int type;
  7. }

Condition对象

调用dao.query(Person.class);就得到了Person类的Condition对象,Condition接口定义了大量添加条件查询的方法.

  1. Condition condition = dao.query(Person.class)
  2. //添加distinct关键字
  3. .distinct()
  4. //username is null
  5. .addNullQuery("username")
  6. //username is not null
  7. .addNotNullQuery("username")
  8. //username is not null and username = ''
  9. .addEmptyQuery("username")
  10. //username is not null and username != ''
  11. .addNotEmptyQuery("username")
  12. //type in (1,2)
  13. .addInQuery("type","1","2")
  14. //type not in (3,4)
  15. .addNotInQuery("type","3","4")
  16. //type between 1 and 2
  17. .addBetweenQuery("type",1,2)
  18. //username like 'quickdao%'
  19. .addLikeQuery("username","quickdao%")
  20. //type >= 1
  21. .addQuery("type",">=","1")

这些方法名见名知义,同时也有详细的JavaDoc文档.所有的查询条件接口以addXXXQuery命名,您可以很方便的分辨出哪些是查询方法接口.

or查询

您可以添加or查询条件

  1. //select distinct id,username,password,type from person where username like 'a%' or username like 'b%'
  2. Condition condition = dao.query(Person.class)
  3. .distinct()
  4. .addLikeQuery("username","a%");
  5. condition.or().addQuery("username","b%")
  6. Response response = condition.execute();

union查询

您可以union多个表,但是您需要保证union关联的表的返回的字段个数保持一致.

您可以指定使用union或者union all类型进行连接,union方法默认采用union连接方式.

  1. Condition unionCondition1 = dao.query(Person.class)
  2. .addQuery("username","a")
  3. .addColumn("username","password");
  4. Condition unionCondition2 = dao.query(Person.class)
  5. .addQuery("username","b")
  6. .addColumn("username","password");
  7. Response response = dao.query(Person.class)
  8. .union(unionCondition1)
  9. .union(unionCondition2,UnionType.UnionAll)
  10. .addColumn("username","password")
  11. .execute();

addRawQuery

addRawQuery方法将给定的参数直接拼接到SQL语句上,适用于查询条件无法用现有API生成的情况

  1. Condition condition = dao.query(Person.class)
  2. .addRawQuery("username = (select max(username) from person where age = t.age) ")

Response 对象

调用Condition实例的execute()方法就得到Response实例对象.Response接口定义获取返回结果的方法.不同的返回结果对应着不同的查询条件.

  1. Condition condition = dao.query(User.class);
  2. Response response = condition.execute();
  3. List<User> userList = response.getList();

clone方法

Condition实现了Cloneable接口.