Implement conditional Query

Source: Internet
Author: User

Step 1:

Interface Definition:

Public interface ICommonDao <T> {

List <T> findCollectionByConditionNoPage (String codition, Object [] params, Map <String, String> 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 <T> findCollectionByConditionNoPage (String condition, final Object [] params, Map <String, String> orderby) {// define the hql statement String hql = "FROM" + entityClass. getSimpleName () + "o WHERE 1 = 1"; // define the sorting statement String orderb YHql = this. orderbyHql (orderby); // defines the final Statement final String finalHql = hql + condition + orderbyHql; // executes Statement 1 // List <T> list = this. getHibernateTemplate (). find (finalHql, params); // execute Statement 2 // SessionFactory sf = this. getHibernateTemplate (). getSessionFactory (); // Session s = sf. getCurrentSession (); // Query query = s. createQuery (finalHql); // List <T> list = query. list (); // execute statement three List <T> list = this. getHibernateTemplate (Cmd.exe cute (new HibernateCallback () {public Object doInHibernate (Session session) throws HibernateException, SQLException {Query query = session. createQuery (finalHql); if (params! = Null & params. length> 0) {for (int I = 0; I <params. length; I ++) {query. setParameter (I, params [I]) ;}} return query. list () ;}}); return list;}/** statement for organizing and sorting * // * order by o. textDate ASC, o. textName DESC */private String orderbyHql (Map <String, String> orderby) {StringBuffer buffer = new StringBuffer (""); if (orderby! = Null & orderby. size ()> 0) {buffer. append ("order by"); for (Map. entry <String, String> 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<ElecText> 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 <ElecText> findCollectionByConditionNoPage (ElecText elecText) {// query condition String condition = ""; list <Object> paramsList = new ArrayList <Object> (); // determines whether to add the query condition if (StringUtils. isNotBlank (elecText. getTextName () {c Ondition + = "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 <String, String> orderby = new LinkedHashMap <String, String> (); orderby. put ("o. textDate "," asc "); orderby. put ("o. textName "," desc "); // query List <ElecText> 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 <ElecText> list = elecTextService. findCol LectionByConditionNoPage (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 elecSystemDDL = this. getModel (); @ Resource (name = IElecSystemDDLService. SERVICE_NAME) private IElecSystemDDLService elecSystemDDLService; public String home () {List <ElecSystemDDL> 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 List <ElecSystemDDL> 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.


Zookeeper

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.