Implement conditional Query

Source: Internet
Author: User
Step 1: Define the interface: publicinterfaceICommonDaoT {ListTfindCollectionByConditionNoPage (Stringcodition, Object [] params, MapString, Stringorderby);} Step 2: implement the Interface Class: ClassentityClassTUtils. getTClass (this. getClass (); publiccl

Step 1: Define the interface: public interface ICommonDaoT {ListT findCollectionByConditionNoPage (String codition, Object [] params, MapString, String orderby);} Step 2: implement the interface class: class entityClass = TUtils. getTClass (this. getClass (); public cl

Step 1:

Interface Definition:

Public interface ICommonDao {

List FindCollectionByConditionNoPage (String codition, Object [] params, Map Orderby );

}

Step 2:
Classes that implement interfaces:

Class entityClass = TUtils. getTClass (this. getClass (); public class TUtils {/** generic conversion. The objective is to obtain the real type of the Child class passed to the parent class, that is, the type corresponding to T */public static Class getTClass (Class entity) {ParameterizedType type = (ParameterizedType) entity. getGenericSuperclass (); Class entityClass = (Class) type. getActualTypeArguments () [0]; return entityClass ;}}
/** Specify the corresponding results of the query condition query AND return the List (not paging) * // *** FROM ElecText o WHERE 1 = 1 # Dao layer AND o. textName LIKE '% sheets %' # Service layer AND o. textRemark LIKE '% sheets %' # Service layer order by o. textDate ASC, o. textName DESC # Service layer */public List
 
  
FindCollectionByConditionNoPage (String condition, final Object [] params, Map
  
   
Orderby) {// define the hql statement String hql = "FROM" + entityClass. getSimpleName () + "o WHERE 1 = 1"; // define the sorting statement String orderbyHql = this. orderbyHql (orderby); // defines the final Statement final String finalHql = hql + condition + orderbyHql; // executes Statement 1 // List
   
    
List = this. getHibernateTemplate (). find (finalHql, params); // execute Statement 2 // SessionFactory sf = this. getHibernateTemplate (). getSessionFactory (); // Session s = sf. getCurrentSession (); // Query query = s. createQuery (finalHql); // List
    
     
List = query. list (); // execute Statement 3 List
     
      
List = this.gethibernatetemplate(cmd.exe cute (new HibernateCallback () {public Object doInHibernate (Session session) throws HibernateException, SQLException {Query query Query = session. createQuery (finalHql); if! = Null & params. length> 0) {for (int I = 0; I
      
        Orderby) {StringBuffer buffer = new StringBuffer (""); if (orderby! = Null & orderby. size ()> 0) {buffer. append ("order by"); for (Map. Entry
       
         Map: orderby. entrySet () {buffer. append (map. getKey () + "" + map. getValue () + ",") ;}// Delete the last comma buffer. deleteCharAt (buffer. length ()-1);} return buffer. toString ();}
       
      
     
    
   
  
 

The following describes how to write different codes based on different services.

Step 3:

Service Interface:

public interface IElecTextService {public static final String SERVICE_NAME = "com.itheima.elec.service.impl.ElecTextServiceImpl";List
 
   findCollectionByConditionNoPage(ElecText elecText);}
 

Step 4:

Service implementation

/** Specify the query condition query result, AND return List * // *** FROM ElecText o WHERE 1 = 1 # Dao layer AND o. textName LIKE '% sheets %' # Service layer AND o. textRemark LIKE '% sheets %' # Service layer order by o. textDate ASC, o. textName DESC # Service layer */public List
 
  
FindCollectionByConditionNoPage (ElecText elecText) {// query condition String condition = ""; List
  ParamsList = new ArrayList(); // Determine whether to add the query condition if (StringUtils. isNotBlank (elecText. getTextName () {condition + = "and o. textName like? "; ParamsList. add ("%" + elecText. getTextName () + "%");} if (StringUtils. isNotBlank (elecText. getTextRemark () {condition + = "and o. textRemark like? "; ParamsList. add ("%" + elecText. getTextRemark () + "%");} Object [] params = paramsList. toArray (); // sorting statement (the hql and SQL statements are sorted by a sequential Map.
    
     
Orderby = new LinkedHashMap
     
      
(); Orderby. put ("o. textDate", "asc"); orderby. put ("o. textName", "desc"); // query List
      
        List = elecTextDao. findCollectionByConditionNoPage (condition, params, orderby); return list ;}
       


Step 5:

/** Simulate Action, call Service, specify the query condition query result, and return List */@ Testpublic void findCollectionByConditionNoPage () {ApplicationContext ac = new ClassPathXmlApplicationContext ("beans. xml "); IElecTextService elecTextService = (IElecTextService) ac. getBean (IElecTextService. SERVICE_NAME); ElecText elecText = new ElecText (); // elecText. setTextName ("Zhang"); // elecText. setTextRemark ("Zhang"); List
        
         
List = elecTextService. findCollectionByConditionNoPage (elecText); if (list! = Null & list. size ()> 0) {for (ElecText elecText2: list) {System. out. println (elecText2.getTextName () + "" + elecText2.getTextDate () + "" + elecText2.getTextRemark ());}}}
        


Real action:

Package com. itheima. elec. web. action; import java. util. list; import javax. annotation. resource; import org. springframework. context. annotation. scope; import org. springframework. stereotype. controller; import com. itheima. elec. domain. elecSystemDDL; import com. itheima. elec. service. IElecSystemDDLService; @ SuppressWarnings ("serial") @ Controller ("elecSystemDDLAction") @ Scope (value = "prototype") public class ElecSystemDDLAction extends BaseAction
        
         
{ElecSystemDDL elecSystemDDL = this. getModel (); @ Resource (name = IElecSystemDDLService. SERVICE_NAME) private IElecSystemDDLService elecSystemDDLService; public String home () {List
         
          
List = elecSystemDDLService. findKeywordWithDistinct (); request. setAttribute ("list", list); return "home";} public String edit () {// obtain the data type String keyword = elecSystemDDL. getKeyword (); // 1: use the data type as the query condition to query the data dictionary table and return the List
          
           
List
           
            
List = elecSystemDDLService. findSystemDDLListByKeyword (keyword); request. setAttribute ("systemList", list); return "edit ";}}
           
          
         
        
Summary: according to what kind of condition query is completed at the service layer, after all the conditions are organized, the dao layer and dao layer are spliced with SQL or hql statements, for real queries. The action at the web layer only transmits parameters to call the methods at the service layer. Bytes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.