SSH与SSM学习之hibernate21——离线查询
一、离线查询说明
我们在使用查询的时候,都是Service通过传递参数调用Dao相应的查询方法。这样有个问题就是我们的查询方法都是固定的。比如我们通过id查询用户,那么就只能通过id查询用户,不能再通过其他方式查询。这样这个方法写的方法就比较多啦。那么我们想要是实现的就是,Dao 内部只做有一个简单的查询,Service等来指定查询的方法等这样的方式怎么做呢?
这就是我们要使用的离线查询了(DetachedCriteria)。
二、非离线查询和离线查询示意图
非离线查询
离线查询
三、代码实例
package com.qwm.hibernate03.c_dc;
import com.qwm.hibernate03.domain.Customer;
import com.qwm.hibernate03.utils.HibernateUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;
import java.util.List;
/**
* @author:qiwenming
* @date:2017/9/20 0020 23:28
* @description:
* 离线查询实例
*/
public class Demo {
@Test
public void test1(){
//代表service/web层过来的
DetachedCriteria dc = DetachedCriteria.forClass(Customer.class);
dc.add(Restrictions.eq("id",1L));
//查询
query(dc);
}
/**
* 查询方法
* @param dc
*/
public void query(DetachedCriteria dc){
Session session = HibernateUtils.openSession();
Transaction t = session.beginTransaction();
Criteria c = dc.getExecutableCriteria(session);
List list = c.list();
System.out.println(list);
t.commit();
session.close();
}
}
四、结果
Hibernate:
alter table cst_linkman
add constraint FKh9yp1nql5227xxcopuxqx2e7q
foreign key (lkm_cust_id)
references cst_customer (cust_id)
Hibernate:
alter table sys_user_role
add constraint FKhh52n8vd4ny9ff4x9fb8v65qx
foreign key (role_id)
references sys_role (role_id)
Hibernate:
alter table sys_user_role
add constraint FKb40xxfch70f5qnyfw8yme1n1s
foreign key (user_id)
references sys_user (user_id)
Hibernate:
select
this_.cust_id as cust_id1_0_0_,
this_.cust_name as cust_nam2_0_0_,
this_.cust_source as cust_sou3_0_0_,
this_.cust_industry as cust_ind4_0_0_,
this_.cust_level as cust_lev5_0_0_,
this_.cust_linkman as cust_lin6_0_0_,
this_.cust_phone as cust_pho7_0_0_,
this_.cust_mobile as cust_mob8_0_0_
from
cst_customer this_
where
this_.cust_id=?
Hibernate:
select
linkmens0_.lkm_cust_id as lkm_cus10_1_0_,
linkmens0_.lkm_id as lkm_id1_1_0_,
linkmens0_.lkm_id as lkm_id1_1_1_,
linkmens0_.lkm_gender as lkm_gend2_1_1_,
linkmens0_.lkm_name as lkm_name3_1_1_,
linkmens0_.lkm_phone as lkm_phon4_1_1_,
linkmens0_.lkm_email as lkm_emai5_1_1_,
linkmens0_.lkm_qq as lkm_qq6_1_1_,
linkmens0_.lkm_mobile as lkm_mobi7_1_1_,
linkmens0_.lkm_memo as lkm_memo8_1_1_,
linkmens0_.lkm_position as lkm_posi9_1_1_,
linkmens0_.lkm_cust_id as lkm_cus10_1_1_
from
cst_linkman linkmens0_
where
linkmens0_.lkm_cust_id=?
[Customer{cust_id=1, cust_name='吊毛公司', cust_source='null', cust_industry='null', cust_level='null', cust_linkman='null', cust_phone='null', cust_mobile='null', linkMens=[com.qwm.hibernate03.domain.LinkMan@6034e75d, com.qwm.hibernate03.domain.LinkMan@5e63cad]}]