java学习笔记

示例涉及的技术点:使用ext做前后端数据传输、sql语句拼接技巧、hql分页查询、hql模板类的编写

示例描述:在网页上输入姓名、部门名称、职务的条件进行信息查询

首先定义页面上的查询按钮,访问查询接口

                    buttons : [{
                                text : '查询',
                                handler : function() {
                                    var data = form.getForm().getValues();
                                    Ext.apply(_this.currStore.baseParams, {
                                        args : Ext.encode(data) 
                                        });
//传入条件参数并加载store进行查询
                                    _this.currStore.load({
                                                params : {
                                                    args : Ext.encode(data)
                                                }
                                            });
                                }
                            }, {
                                text : '重置',
                                handler : function() {
                                    form.getForm().reset();
                                }
                            }],
                    items : [{
                                layout : 'column',
                                items : [{
                                            columnWidth : .33,
                                            layout : 'form',
                                            items : [{
                                                        xtype : 'textfield',
                                                        fieldLabel : '姓名',
                                                        name : 'xm',
                                                        maxLength : 20,
                                                        anchor : '90%'
                                                    }]
                                        }, {
                                            columnWidth : .33,
                                            layout : 'form',
                                            items : [{
                                                        xtype : 'textfield',
                                                        fieldLabel : '部门名称',
                                                        name : 'deptName',
                                                        anchor : '90%'
                                                    }]
                                        },{
                                            columnWidth : .33,
                                            layout : 'form',
                                            items : [{
                                                        xtype : 'textfield',
                                                        fieldLabel : '职务',
                                                        name : 'zwmc',
                                                        anchor : '90%'
                                                    }]
                                        }]
                            }]

然后定义store的结构:

        var store = new Ext.data.JsonStore({
                    url : _this.queryUrl,
                    baseParams : {
                        args : "{}",
                        start : 0,
                        limit : config.PAGE_SIZE
                    },
                    totalProperty : 'result.total',
                    root : 'result.list',
                    fields : ['tid', 'xm', 'mobilePhone1', 'telephone',
                            'email', 'skype', 'sfzh', 'mobilePhone1', 'fax',
                            'qq', 'comment','deptName','deptId','email2','csrq',
                        'lxmc','xlmc','zwmc','lxid','xlid','zwid','sex','email2','dqqxpz','ysdwId','ysdwmc','is_ysdwry']
                });
        store.load();
        this.currStore = store;

从中可以看出store的数据加载来自于queryUrl接口,这是一个用springmvc做的controller。这个接口在js文件中引入:

queryUrl : getRootPath() + "sys/ygxx/queryPagerByCxtj",

其响应的controller的实现:

    @RequestMapping("/queryPagerByCxtj")
    public ModelAndView queryPagerByCxtj(String args, int start, int limit) {
        try {
            YgxxSearchBean ygxxSearch = JSON.parseObject(args, YgxxSearchBean.class);
            Pager pager = ygxxService.queryPageByCxtj(ygxxSearch, start, limit);
            return handlerSuccess("分页查询员工成功", pager);
        } catch (RuntimeException e) {
            return handlerException("分页查询员工失败", e);
        }
    }

服务层的接口与实现为:

public Pager queryPageByCxtj(YgxxSearchBean ygxxSearch, int start, int limit);
    public Pager queryPageByCxtj(YgxxSearchBean ygxxSearch, int start, int limit) {
        return ygxxDao.queryPageByCxtj(ygxxSearch, start, limit);
    }

其调用的dao层的接口与实现为:

public Pager queryPageByCxtj(YgxxSearchBean ygxxSearch,int start, int limit);
    public Pager queryPageByCxtj(YgxxSearchBean ygxxSearch, int start, int limit) {
        Map res = getHql(ygxxSearch);
        String hql = (String) res.get("hql");
        Map parameter = (Map) res
                .get("parameter");
        return getHqlQuery().findPager(hql.toString(), parameter, start, limit);
    }

首先显然这里用了一个getHql()方法去拼接要求的hql语句。
以下是底层sql语句的拼接(值得分析):

    private Map getHql(YgxxSearchBean bean) {
        StringBuffer hql = new StringBuffer(
                "from Ygxx ygxx where ygxx.logicaldeletecode = 0 and ygxx.xm != 'sss' and ygxx.xm != 'sss' ");
        Map res = new HashMap();
        Map parameter = new HashMap();

        if (bean != null) {
            if (bean.getDeptId() != null) {
                hql.append(" and ygxx.deptId = :deptId");
                parameter.put("deptId", bean.getDeptId());
            }

            if (!Utils.isEmpty(bean.getDeptName())) {
                hql.append(" and ygxx.deptName like :deptName");
                parameter.put("deptName", "%" + bean.getDeptName() + "%");
            }

            if (!Utils.isEmpty(bean.getZwmc())) {
                hql.append(" and ygxx.zwmc like :zwmc");
                parameter.put("zwmc", "%" + bean.getZwmc() + "%");
            }

            if (!Utils.isEmpty(bean.getXm())) {
                hql.append(" and ygxx.xm like :xm");
                parameter.put("xm", "%" + bean.getXm() + "%");
            }
            
            if(Utils.isNotEmpty(bean.getMobilePhone1())) {
                hql.append(" and ygxx.mobilePhone1 like :mobilePhone1");
                parameter.put("mobilePhone1", "%" + bean.getMobilePhone1() + "%");
            }
            
            if(Utils.isNotEmpty(bean.getMobilePhone2())) {
                hql.append(" and ygxx.mobilePhone2 like :mobilePhone2");
                parameter.put("mobilePhone2", "%" + bean.getMobilePhone2() + "%");
            }
            
            
            if(Utils.isNotEmpty(bean.getTelephone())) {
                hql.append(" and ygxx.telephone like :telephone");
                parameter.put("telephone", "%" + bean.getTelephone() + "%");
            }
            
            if(Utils.isNotEmpty(bean.getEmail())) {
                hql.append(" and ygxx.email like :email");
                parameter.put("email", "%" + bean.getEmail() + "%");
            }
            
            if(Utils.isNotEmpty(bean.getFax())) {
                hql.append(" and ygxx.fax like :fax");
                parameter.put("fax", "%" + bean.getFax() + "%");
            }
            
            if(Utils.isNotEmpty(bean.getYgids())) {
                hql.append(" and ygxx.tid in (").append(bean.getYgids()).append(")");
            }
            
        }

        hql.append(" order by tid desc ");
        res.put("hql", hql.toString());
        res.put("parameter", parameter);
        return res;
    }

其次这里的return语句中的getHqlQuery().findPager()方法也值得深思。
以下是该findPager()方法的实现:

public Pager findPager(String queryString, Map parameters, int start, int limit) {
            Assert.INSTANCE.assertNotEmpty("queryString is empty", queryString);
            Assert.INSTANCE.assertNotNull("parameters is null", parameters);
            Assert.INSTANCE.assertTrue("start < 0", start >= 0);
            Assert.INSTANCE.assertTrue("limit <= 0", limit > 0);
            HibernateCallback callback = createQueryForPagerHibernateCallback(queryString, parameters, start,
                    limit);
            return getHibernateTemplate().execute(callback);
        }

这里的return语句依旧调用了hibernate模板方法:

    public  T execute(HibernateCallback action) throws DataAccessException {
        return this.doExecute(action, false, false);
    }

自己调了doExecute()方法:

    protected  T doExecute(HibernateCallback action, boolean enforceNewSession, boolean enforceNativeSession) throws DataAccessException {
        Assert.notNull(action, "Callback object must not be null");
        Session session = enforceNewSession ? SessionFactoryUtils.getNewSession(this.getSessionFactory(), this.getEntityInterceptor()) : this.getSession();
        boolean existingTransaction = !enforceNewSession && (!this.isAllowCreate() || SessionFactoryUtils.isSessionTransactional(session, this.getSessionFactory()));
        if (existingTransaction) {
            this.logger.debug("Found thread-bound Session for HibernateTemplate");
        }

        FlushMode previousFlushMode = null;

        Object var9;
        try {
            previousFlushMode = this.applyFlushMode(session, existingTransaction);
            this.enableFilters(session);
            Session sessionToExpose = !enforceNativeSession && !this.isExposeNativeSession() ? this.createSessionProxy(session) : session;
            T result = action.doInHibernate(sessionToExpose);
            this.flushIfNecessary(session, existingTransaction);
            var9 = result;
        } catch (HibernateException var15) {
            throw this.convertHibernateAccessException(var15);
        } catch (SQLException var16) {
            throw this.convertJdbcAccessException(var16);
        } catch (RuntimeException var17) {
            throw var17;
        } finally {
            if (existingTransaction) {
                this.logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
                this.disableFilters(session);
                if (previousFlushMode != null) {
                    session.setFlushMode(previousFlushMode);
                }
            } else if (this.isAlwaysUseNewSession()) {
                SessionFactoryUtils.closeSession(session);
            } else {
                SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, this.getSessionFactory());
            }

        }

        return var9;
    }

到此已到底部。

你可能感兴趣的:(java学习笔记)