ExtJs 4.2 Application: Using ExtJs Extension Component searchfield to Realize Data Search Function

Keywords: Session Java SQL Hibernate

Links to the original text: https://my.oschina.net/qiuzhping/blog/611700

ExtJs 4.2 Application: Extending component search field with ExtJs

Implementing Data Search Function

1. Introducing searchfield component

Put the searchfield component in the form file under the ux directory under the Ext directory, as shown in the figure:

2. Introducing searchfield components into corresponding Js files

dockedItems: [{  
	        dock: 'top',   /**Display at the top*/
	        xtype: 'toolbar', /**Display in toolbar form*/  
	        items: {   
	            width: "25%",
	            fieldLabel: 'Login Name:',
	            labelWidth:100,
	            xtype: 'searchfield',/**searchfield ExtJs Extension Component 
	                                The reference path is Ext.Loader.setPath('Ext.ux', rootPath+'/ux/')
	                                rootPath is the Ext class and path: for example, http://localhost:8080/demo/Ext */
	            store: store /**Corresponding data sets*/  
	       }  
	    },{
	        xtype: 'pagingtoolbar',
	        store: store,
	        dock: 'bottom',
	        displayInfo: true
	    }]

3. Complete JS code

Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', rootPath+'/ux/');
Ext.require([
	'Ext.ux.form.SearchField'
]);
var itemsPerPage = 15;
var params;
var store = Ext.create('Ext.data.Store',{
		fields:["id","firstName","lastName","loginName","telephone","brithday","sexId","depId"],
		proxy:{
			type:'ajax',
			url:'/demo/JobData.action',
			reader:{
				type:'json',
				root:'rootData',
				totalProperty: 'totalCount'
			}
		},
		pageSize: itemsPerPage,
		autoLoad:true	
});
Ext.onReady(function(){
	Ext.Loader.setConfig({
		enabled:true
	});
	Ext.create('Ext.grid.Panel',{
		title:'Job Enquiry',
		width:'100%',
		layout:"auto",
		style:"margin-left:auto;margin-right:auto;",
		renderTo:Ext.getBody(),
		columns:[{
				header:'Id',
				flex: 1,align:"center", 
				dataIndex:'id',
				sortable:true
			},{
				header : "First Name",  
				flex: 1, align:"center", 
                dataIndex : 'firstName',  
                sortable : true  
			}, {  
                header : "Last Name",  
                flex: 1,  align:"center",
                dataIndex : 'lastName',  
                sortable : true  
            }, {  
                header : "Login Name",  
                flex: 1, 
				align:"center",
                dataIndex : 'loginName',  
                sortable : true  
            }, {  
                header : "Telephone",  
                flex: 1,align:"center",
                hideable: false,
                dataIndex : 'telephone',  
                sortable : true  
            }, {  
                header : "brithday",  
                flex: 1, align:"center", 
                dataIndex : 'brithday',
                sortable : true  
            }, {  
                header : "Sex Id",  
                flex: 1, align:"center", 
                dataIndex : 'sexId',  
                sortable : true  
            }, {  
                header : "Dep Id",  
                flex: 1,  align:"center", 
                dataIndex : 'depId',  
                sortable : true  
            }],
		store:store,
		//style:"margin-left:auto;margin-right:auto;align:center", 
		pageSize: itemsPerPage,
		dockedItems: [{  
	        dock: 'top',   /**Display at the top*/
	        xtype: 'toolbar', /**Display in toolbar form*/  
	        items: {   
	            width: "25%",
	            fieldLabel: 'Login Name:',
	            labelWidth:100,
	            xtype: 'searchfield',/**searchfield ExtJs is an extension component of ExtJs 
	                                The reference path is Ext.Loader.setPath('Ext.ux', rootPath+'/ux/')
	                                rootPath is the Ext class and path: for example, http://localhost:8080/demo/Ext */
	            store: store /**Corresponding data sets*/  
	       }  
	    },{
	        xtype: 'pagingtoolbar',
	        store: store,
	        dock: 'bottom',
	        displayInfo: true
	    }]
	});
	store.load({params:{start:0,limit:itemsPerPage}});
	var startTime;
	var endTime;
	function checkDate(){
		startTime = Ext.getCmp("startTime");
		endTime = Ext.getCmp("endTime");
		if(startTime != null && endTime != null && startTime.getValue() > endTime.getValue()){
			alert("Start time must be smaller than the end time!");
			return false;
		}
		return true;
	}
	function query(){
		//check date 
		if(!checkDate()){
			return ;
		}
		params = {
			'conEnquiryTicketVo.startTime':startTime.getValue(),
			'conEnquiryTicketVo.endTime':endTime.getValue(),
			start:0,
			limit:itemsPerPage
		};
//		store.on('beforeload',function(){
//			var startTime = Ext.getCmp("startTime");
//			var endTime = Ext.getCmp("endTime");
//			//alert("click!!"+startTime.getValue());
//			params = {
//				'conEnquiryTicketVo.startTime':startTime.getValue(),
//				'conEnquiryTicketVo.endTime':endTime.getValue(),
//				start:0,
//				limit:itemsPerPage
//			};
//		});
		store.load({params:params});
	}
});

4. effect picture

The corresponding Java code in the last article:

On this basis, the GetJobDataAction.java content is modified to:
package com.qiuzhping.report.action;

import java.math.BigDecimal;
import java.util.List;

import org.apache.log4j.Logger;

import com.opensymphony.xwork2.ActionSupport;
import com.qiuzhping.report.dao.impl.DepartmentDaoImpl;
import com.qiuzhping.report.domian.Job;

/**
 * <Description functions in a word>
 * <Detail description>
 * 
 * @author  Qiuzhenping
 * @version  [Version NO, 2014-12-5]
 * @see  [Related classes/methods]
 * @since  [product/module version]
 */
public class GetJobDataAction extends ActionSupport{
	/**
	 *serialVersionUID
	 */
	private static final long serialVersionUID = 3288957476157165689L;
	private Logger log = Logger.getLogger(this.getClass());
	private BigDecimal totalCount;
	private List rootData;
	private int start;
	private int limit;
	private String query;<span><span class="comment">/**query The field corresponds to the name of the extended component searchfield, and you can see the source code of the searchfield in detail.*/</span><span></span></span>
	
	public String getQuery() {
		return query;
	}
	public void setQuery(String query) {
		this.query = query;
	}
	public BigDecimal getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(BigDecimal totalCount) {
		this.totalCount = totalCount;
	}
	public List getRootData() {
		return rootData;
	}
	public void setRootData(List rootData) {
		this.rootData = rootData;
	}
	
	public int getStart() {
		return start;
	}
	public void setStart(int start) {
		this.start = start;
	}
	public int getLimit() {
		return limit;
	}
	public void setLimit(int limit) {
		this.limit = limit;
	}
	
	@Override
	public String execute(){
		try {
			DepartmentDaoImpl ddi = new DepartmentDaoImpl();
			log.info("start = "+start);
			log.info("limit = "+limit);
			int end = start+limit;
			log.info("end = "+end);
			totalCount = ddi.getTotalCount(Job.class,query);
			rootData  = ddi.getData(start, limit,Job.class,query);
		} catch (Exception e) {
			log.error(e);
		}
		return SUCCESS;
	}
}

The content of DepartmentDaoImpl.java was modified to:

package com.qiuzhping.report.dao.impl;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.qiuzhping.report.domian.Job;
import com.qiuzhping.report.util.HibernateSessionFactory;

/**
 * <Description functions in a word>
 * <Detail description>
 * 
 * @author  Qiuzhenping
 * @version  [Version NO, 2014-12-5]
 * @see  [Related classes/methods]
 * @since  [product/module version]
 */
public class DepartmentDaoImpl{
	
	private HibernateSessionFactory hsf = HibernateSessionFactory.getInstance();
	
	public BigDecimal getTotalCount(Class clazz,String name){
		Session session = hsf.getSessionFactory().openSession();
		StringBuffer sql = new StringBuffer("SELECT * FROM job ");
		if(name != null){
			sql.append(" WHERE loginName like '%"+name+"%' ");
		}
		SQLQuery query =session.createSQLQuery(sql.toString());
		query.addEntity(clazz);
		return new BigDecimal(query.list().size());
	}
	public List<Job> getData(int start,int end,Class clazz,String name){
		Session session = hsf.getSessionFactory().openSession();
		StringBuffer sql = new StringBuffer("SELECT * FROM job");
		if(name != null){
			sql.append(" WHERE loginName like '%"+name+"%' ");
		}
		sql.append(" LIMIT "+start+","+end);
		SQLQuery query =session.createSQLQuery(sql.toString());
		query.addEntity(clazz);
		return query.list();
	}
	public void save() throws HibernateException, SQLException{
		Session session = hsf.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		for (int i = 0; i < 1000; i++) {
			Job job = new Job();
			job.setId(i + 10);
			job.setBrithday(new Timestamp(System.currentTimeMillis()));
			job.setSexId(0);
			job.setLoginName("qiuzhping"+i);
			job.setLastName("qiuzhping"+i);
			job.setFirstName("qiu"+i);
			job.setDepId(1);
			session.saveOrUpdate(job);
			if (i % 20 == 0) { // The number of single batch operations is 20
				session.flush(); // Clean up the cache and execute the SQL insert statement for batch insertion of 20 records
				session.clear(); // Empty the Customer object in the cache
			}
		}
		tx.commit();
		session.close();
	}

	/** <Description functions in a word>
	 * 
	 * <Detail description>
	 * @author  Qiuzhenping
	 * @param args [Parameters description]
	 * @return void [Return type description]
	 * @throws SQLException 
	 * @throws HibernateException 
	 * @exception throws [Exception] [Exception description]
	 * @see [Related classes#Related methods#Related properties]
	 */
	public static void main(String[] args) throws HibernateException, SQLException {
		//DepartmentDaoImpl ddi = new DepartmentDaoImpl();
		//ddi.save();
		//System.out.println(ddi.getData(0, 25,Job.class).size());
		Field[] fields = Job.class.getDeclaredFields();
		for(Field f :fields){
			System.out.print("\""+f.getName()+"\",");
		}

	}

}


Note: http://blog.csdn.net/qiuzhping/article/details/41811655


ExtJs 4.2 Serial Notes

ExtJs 4.2 Application: ExtJs 4.2 + Mysql + Struts 2 + Hibernate 3 to realize paging query

ExtJs 4.2 Application: Using ExtJs Extension Component searchfield to Realize Data Search Function



Reproduced in: https://my.oschina.net/qiuzhping/blog/611700

Posted by jonathandg on Wed, 02 Oct 2019 12:37:45 -0700