一、对象查询举例
/**
* 对象查询Query:
* asc desc count list listPage singleResult 用法举例
* 用户组表查询举例
*/
@Test
public void testObjectQuery(){
//1.查询list()
List<Group> groupList = identityService.createGroupQuery().list();
if(groupList==null||groupList.size()==0){//如果,没有测试数据,创建10条
for(int i=0;i<10;i++){
Group group=identityService.newGroup(i+"");//创建一个用户组
group.setName("Group_"+i);
group.setType("Type_"+i);
identityService.saveGroup(group);
}
}else{//遍历打印输出
for (Group group : groupList) {
System.out.println(group.getId()+","+group.getName()+","+group.getType());
}
System.out.println("查询list()结束#################################");
}
//2.分页查询listPage()
groupList = identityService.createGroupQuery().listPage(1, 5);
for (Group group : groupList) {
System.out.println(group.getId()+","+group.getName()+","+group.getType());
}
System.out.println("分页查询listPage()结束#################################");
// 3.count()数量
long count = identityService.createGroupQuery().count();
System.out.println("数量count():"+count);
System.out.println("查询count()数量结束#################################");
//4.desc和asc,多个字段排序举例
groupList = identityService.createGroupQuery().orderByGroupName().desc().orderByGroupType().desc().list();
for (Group group : groupList) {
System.out.println(group.getId()+","+group.getName()+","+group.getType());
}
System.out.println("desc和asc结束#################################");
//5.查询singResult(),假如数据库中有多个会抛出异常
Group group = identityService.createGroupQuery().groupName("Group_0").singleResult();
System.out.println(group.getId()+","+group.getName()+","+group.getType());
System.out.println("查询singResult()结束#################################");
}
测试结果:
二、原生SQL查询举例
/**
* 原生SQL查询Query
* 用户组表查询举例
*/
@Test
public void testNativeSql(){
Group group = identityService.createNativeGroupQuery()
.sql("select * from act_id_group where name_=#{name}")
.parameter("name", "Group_2").singleResult();
System.out.println(group.getId()+","+group.getName()+","+group.getType());
}
测试结果: