---
title: "DetachedCriteria构建动态查询"
author: "srj2903"
date: "2009-03-24T13:46:38Z"
tags: []
slug: "detachedcriteria"
draft: false
lastmod: "2009-03-24T13:46:38Z"
id: 354181
url: "https://srj2903.iteye.com/blog/354181"
---

这段代码是项目中的一个方法使用DetachedCriteria构建动态查询

 

 

public List searchInfo(final Page page, final AccountView accountView) {  
        DetachedCriteria dct = DetachedCriteria.forClass(AccountView.class);  
        if(accountView != null){  
            if(accountView.getAccountName() != null && !"".equals(accountView.getAccountName().trim())){  
                dct.add(Restrictions.like("accountName", accountView.getAccountName(),MatchMode.ANYWHERE));  
            }  
            if(accountView.getNameCN() != null && !"".equals(accountView.getNameCN().trim())){  
                dct.add(Restrictions.like("nameCN", accountView.getNameCN(),MatchMode.ANYWHERE));  
            }  
            if(accountView.getDepartmentId() != null && accountView.getDepartmentId()&gt;0){  
                dct.add(Restrictions.eq("departmentId", accountView.getDepartmentId()));  
                dct.add(Restrictions.eq("companyId", accountView.getCompanyId()));  
            }else if(accountView.getCompanyId() != null && accountView.getCompanyId().intValue()&gt;0){  
                dct.add(Restrictions.eq("companyId", accountView.getCompanyId()));  
            }  
            if(accountView.getEmail() != null && !"".equals(accountView.getEmail().trim())){  
                dct.add(Restrictions.like("email", accountView.getEmail(),MatchMode.ANYWHERE));  
            }  
            if(accountView.getUserPosition() != null && !"".equals(accountView.getUserPosition().trim())){  
                dct.add(Restrictions.like("userPosition", accountView.getUserPosition(),MatchMode.ANYWHERE));  
            }  
        }  
        if(page == null){  
            return super.findByCriteria(dct);  
        }else{  
            return super.findByCriteria(dct, page);  
        }  
    }