zoukankan      html  css  js  c++  java
  • 按照用户名和角色查询用户liferay

    需求:当登录的用户输入用户的名字和角色的时候,模糊查询,然后就是Ajax的异步请求刷新界面

    首先在一个工具类中写上一条你要写的sql语句代码如下:

    package com.ebizwindow.crm.utils;

    import java.util.List;

    import com.ebizwindow.crm.constants.SqlConst;
    import com.ebizwindow.crm.constants.TableConst;
    import com.ebizwindow.crm.model.TableDefinition;
    import com.ebizwindow.crm.portlet.base.SystemStatus;
    import com.ebizwindow.crm.service.OpportunityLocalServiceUtil;
    import com.ebizwindow.crm.service.TableDefinitionLocalServiceUtil;
    import com.liferay.portal.kernel.exception.PortalException;
    import com.liferay.portal.kernel.exception.SystemException;
    import com.liferay.portal.kernel.util.StringPool;

    public class SQLUtil {
        private static final String PK_COLUMN_CREATEUSERID = "createUserId";
        private static final String PK_COLUMN_EDITUSERID = "editUserId";
        private static final String PK_COLUMN_AUDITUSERID = "auditUserId";
        private static final String PK_COLUMN_CLOSEUSERID = "closeUserId";
        private static final String PK_COLUMN_CONFIRMUSERID = "confirmUserId";
        private static final String PK_COLUMN_REQUESTUSERID = "requestUserId";
        private static final String PK_COLUMN_EXECUTORID = "executorId";
        private static final String PK_COLUMN_SUBMITUSERID = "submitUserId";
        private static final String PK_COLUMN_OWNERID = "ownerId";
        private static final String PK_COLUMN_UPID = "upId";
        private static final String PK_COLUMN_CUSTOMERID = "customerId";
        private static final String PK_COLUMN_CONTACTID = "contactId";
        private static final String PK_COLUMN_CONTRACTID = "contractId";
        private static final String PK_COLUMN_OPPORTUNITYID = "opportunityId";
        private static final String PK_COLUMN_QUOTATIONID = "quotationId";
        private static final String PK_COLUMN_CLUEID = "clueId";
        private static final String PK_COLUMN_ACTIVITYID = "activityId";
        private static final String PK_COLUMN_MARKETID = "marketId";
        private static final String PK_COLUMN_SALESTEMPLATEID = "salesTemplateId";
        private static final String PK_COLUMN_DEPARTMENTID = "departmentId";
        private static final String PK_COLUMN_PRODUCTID = "productId";
        private static final String PK_COLUMN_PROJECTID = "projectId";

        public static String getQueryValue(String queryValue, String columnName, long companyId) throws SystemException {
            String results = StringPool.BLANK;
            String query = StringPool.BLANK;
            if (columnName.equals(PK_COLUMN_CREATEUSERID)
                    || columnName.equals(PK_COLUMN_EDITUSERID)
                    || columnName.equals(PK_COLUMN_AUDITUSERID)
                    || columnName.equals(PK_COLUMN_OWNERID)
                    || columnName.equals(PK_COLUMN_CLOSEUSERID)
                    || columnName.equals(PK_COLUMN_CONFIRMUSERID)
                    || columnName.equals(PK_COLUMN_REQUESTUSERID)
                    || columnName.equals(PK_COLUMN_SUBMITUSERID)
                    || columnName.equals(PK_COLUMN_EXECUTORID) ) {

                query = "select userId from User_ where firstName like '%" + queryValue + "%'";
                
            } else if (columnName.equals(PK_COLUMN_UPID) || columnName.equals(PK_COLUMN_CUSTOMERID)) {
                
                query = "select customerId from CRM_Customer where chineseName like '%" + queryValue + "%'";
            
            } else if (columnName.equals(PK_COLUMN_CONTACTID)) {
                
                query = "select contactId from CRM_Contact where chineseName like '%" + queryValue + "%'";

            } else if (columnName.equals(PK_COLUMN_MARKETID)) {
                
                query = "select marketId from CRM_Market where name like '%" + queryValue + "%'";
        
            } else if (columnName.equals(PK_COLUMN_CLUEID)) {
                
                query = "select clueId from CRM_Clue where name like '%" + queryValue + "%'";
        
            } else if (columnName.equals(PK_COLUMN_OPPORTUNITYID)) {
                
                query = "select opportunityId from CRM_Opportunity where topic like '%" + queryValue + "%'";
        
            } else if (columnName.equals(PK_COLUMN_QUOTATIONID)) {
                
                query = "select quotationId from CRM_Quotation where name like '%" + queryValue + "%'";
        
            } else if (columnName.equals(PK_COLUMN_CONTRACTID)) {
                
                query = "select contractId from CRM_Contract where name like '%" + queryValue + "%'";
        
            } else if (columnName.equals(PK_COLUMN_ACTIVITYID)) {
                
                query = "select activityId from CRM_Activity where name like '%" + queryValue + "%'";
        
            } else if (columnName.equals(PK_COLUMN_SALESTEMPLATEID)) {
                
                query = "select salesTemplateId from CRM_SalesTemplate where name like '%" + queryValue + "%'";
        
            } else if (columnName.equals(PK_COLUMN_PRODUCTID)) {
                
                query = "select productId from CRM_Product where name like '%" + queryValue + "%'";
                
            } else if (columnName.equals(PK_COLUMN_DEPARTMENTID)) {
                
                query = "select departmentId from OPERATOR_Department where departmentName like '%" + queryValue + "%'";

            } else if (columnName.equals(PK_COLUMN_PROJECTID)) {
                
                query = "select projectId from CRM_Project where name like '%" + queryValue + "%'";

            }
            
            query += " and companyId = '" + companyId + "'";
            
            List<Long> entityIDs = OpportunityLocalServiceUtil.searchBySQLQueryString(query, -1, -1);
            
            String entityIDsStr = entityIDs.toString();
            results = StringPool.OPEN_PARENTHESIS + entityIDsStr.subSequence(1, entityIDsStr.length() - 1) + StringPool.CLOSE_PARENTHESIS;

            return results;
        }
        
        //private static Log _log = LogFactoryUtil.getLog(BasePortlet.class);

        public static String symbolToString(String symbol, String value) {
            String str = StringPool.BLANK;
            if (!symbol.equals(StringPool.BLANK)) {
                if (symbol.equals("eq") || symbol.equals(StringPool.EQUAL)) {

                    str = " = '" + value + "'";

                } else if (symbol.equals("gt") || symbol.equals(StringPool.GREATER_THAN)) {

                    str = " > '" + value + "'";

                } else if (symbol.equals("lt") || symbol.equals(StringPool.LESS_THAN)) {

                    str = " < '" + value + "'";

                } else if (symbol.equals("gteq") || symbol.equals(StringPool.GREATER_THAN_OR_EQUAL)) {

                    str = " >= '" + value + "'";

                } else if (symbol.equals("lteq") || symbol.equals(StringPool.LESS_THAN_OR_EQUAL)) {

                    str = " <= '" + value + "'";

                } else if (symbol.equals("ne") || symbol.equals(StringPool.NOT_EQUAL)) {

                    str = " <> '" + value + "'";

                } else if (symbol.equals("c")) {

                    str = " like '%" + value + "%'";

                } else if (symbol.equals("sl")) {

                    str = " like '" + value + "%'";
                    
                } else if (symbol.equals("sr")) {

                    str = " like '%" + value + "'";

                } else if (symbol.equals("nn")) {

                    str = " <> '' ";

                } else if (symbol.equals("n")) {

                    str = " = '' ";
                    
                } else if (symbol.equals("isn")) {

                    str = " is null ";
                } else if (symbol.equals("!eq")) {
                    
                    str = " != '" + value + "'";
                    
                } else if (symbol.equals("tc")) {
                    
                    str = " in " + value + " ";
                    
                }
            } else {
                str = " = '' ";
            }
            return str;
        }

        public static String getActivitySQL(long userId) throws SystemException {
            StringBuffer sb = new StringBuffer("select activity.activityId from CRM_Activity activity where (activity.executorId in ")
                .append(OperatorUtil.searchViewOperatorIds(userId,TableConst.ACTIVITY))
                .append(" or activity.createUserId in ")
                .append(OperatorUtil.searchViewOperatorIds(userId,TableConst.ACTIVITY))
                .append(")");
            return sb.toString();
        }
        
        public static String getCustomerSQL(long userId) throws SystemException {
            String sql = "select customer.customerId from CRM_Customer customer where 1=1 and (customer.ownerId in "
                + OperatorUtil.searchViewOperatorIds(userId, TableConst.CUSTOMER) + ")";
            
            return sql;
        }

        public static String getCustomerSQL4Dialog(long userId) throws SystemException {
            String sql = "select customer.customerId from CRM_Customer customer where customer.ownerId = '" + userId + "'";
            return sql;
        }
        
        public static String getContactSQL(long userId) throws SystemException {
            String sql = "select contact.contactId from CRM_Contact contact where (contact.ownerId in "
                + OperatorUtil.searchViewOperatorIds(userId,TableConst.CONTACT) + ")";
            return sql;
        }
        
        public static String getContactTop10SQL(long userId) throws SystemException {
            String sql = "select contact.contactId from CRM_Contact contact where (contact.ownerId in "
                    + OperatorUtil.searchViewOperatorIds(userId,TableConst.CONTACT) + ") order by contact.createDate limit 10 ";
            return sql;
        }

        public static String getContractSQL(long userId) throws SystemException {
            String sql = "select contract.contractId from CRM_Contract contract where (contract.ownerId in "
                    + OperatorUtil.searchViewOperatorIds(userId,TableConst.CONTRACT) + ")";
            return sql;
        }
        
        public static String getMarketSQL(long userId) throws SystemException {
            String sql = "select market.marketId from CRM_Market market where (market.ownerId in "
                    + OperatorUtil.searchViewOperatorIds(userId,TableConst.MARKET)  + ")";
            return sql;
        }

        public static String getClueSQL(long userId) throws SystemException {
            String sql = "select clue.clueId from CRM_Clue clue where (clue.ownerId in "
                + OperatorUtil.searchViewOperatorIds(userId,TableConst.CLUE) + ") and clue.auditStatus='"+SystemStatus.Audit.getStatus()+"'";
            return sql;
        }
        
        public static String getOpportunitySQL(long userId) throws SystemException {
            String sql = "select opportunity.opportunityId from CRM_Opportunity opportunity where (opportunity.ownerId in "
                + OperatorUtil.searchViewOperatorIds(userId,TableConst.OPPORTUNITY) + ")";
            return sql;
        }

        public static String getOpportunityTop10SQL(long userId) throws SystemException {
            String sql = "select opportunity.opportunityId from CRM_Opportunity opportunity where (opportunity.ownerId in "
                    + OperatorUtil.searchViewOperatorIds(userId,TableConst.OPPORTUNITY) + ") order by opportunity.createDate limit 10";
            return sql;
        }

        public static String getQuotationSQL(long userId) throws SystemException {
            String sql = "select quotation.quotationId from CRM_Quotation quotation where (quotation.ownerId in "
                    + OperatorUtil.searchViewOperatorIds(userId,TableConst.QUOTATION) + ")";
            return sql;
        }
        
        public static String getOrderSQL(long userId) throws SystemException {
            String sql = "select order_.orderId from CRM_Order order_ where (order_.ownerId in "
                + OperatorUtil.searchViewOperatorIds(userId,TableConst.ORDER) + ")";
            
            return sql;
        }

        public static String getProductSQL(long companyId) throws SystemException {
            String sql = "select product.productId from CRM_Product product where product.companyId = '" + companyId + "'";
            return sql;
        }

        public static String getProjectSQL(long companyId) throws SystemException {
            String sql = "select project.projectId from CRM_Project project where project.companyId = '" + companyId + "'";
            return sql;
        }

        public static String getRPlanSQL(long userId) throws SystemException {
            String sql = "select receivablesPlan.receivablesPlanId from CRM_ReceivablesPlan receivablesPlan where (receivablesPlan.ownerId in "
                 + OperatorUtil.searchViewOperatorIds(userId,TableConst.RPLAN) + ")";
            return sql;
        }
        
        public static String getRRecordSQL(long userId) throws SystemException{
            String sql = "select receivablesRecord.receivablesRecordId from CRM_ReceivablesRecord receivablesRecord where (receivablesRecord.ownerId in "
                 + OperatorUtil.searchViewOperatorIds(userId,TableConst.RRECORD) + ")";
            return sql;
        }
        
        public static String getCreditRightsSQL(long userId) throws SystemException{
            String sql = "select credit.CRId from CR_CreditRights credit where (credit.ownerId in " +
                OperatorUtil.searchViewOperatorIds(userId,TableConst.CreditRights)+" ) ";
            return sql;
        }
        
        //得到部门下的所有的用户
        public static String getOperatorSQL(long departmentId) throws SystemException{
            //select operator.operatorId from Operator_operator as operator where operator.departmentId in (204);
            String sql = "select operator.operatorId from Operator_operator as operator where (operator.operatorId in "+OperatorUtil.searchViewOperatorIds(departmentId,TableConst.OPERATOR_Operator)+")";
            
            return sql;
            
        }

        public static String getSQLBeginningByTableDefinitionId(long tableDefinitionId) throws PortalException, SystemException {
            String result = "";
            TableDefinition tableDefinition = TableDefinitionLocalServiceUtil.getTableDefinition(tableDefinitionId);
            String tableName = tableDefinition.getTableName();
            if (tableName.equals(TableConst.CRM_Customer)) {
                result = SqlConst.CUSTOMER_SQL_BEGINNING;
            } else if (tableName.equals(TableConst.CRM_Customer)) {
                result = SqlConst.CUSTOMER_SQL_BEGINNING;
            } else if (tableName.equals(TableConst.CRM_Contact)) {
                result = SqlConst.CONTACT_SQL_BEGINNING;
            } else if (tableName.equals(TableConst.CRM_Market)) {
                result = SqlConst.MARKET_SQL_BEGINNING;
            } else if (tableName.equals(TableConst.CRM_Clue)) {
                result = SqlConst.CLUE_SQL_BEGINNING;
            } else if (tableName.equals(TableConst.CRM_Activity)) {
                result = SqlConst.ACTIVITY_SQL_BEGINNING;
            } else if (tableName.equals(TableConst.CRM_Opportunity)) {
                result = SqlConst.OPPORTUNITY_SQL_BEGINNING;
            } else if (tableName.equals(TableConst.CRM_Quotation)) {
                result = SqlConst.QUOTATION_SQL_BEGINNING;
            } else if (tableName.equals(TableConst.CRM_Contract)) {
                result = SqlConst.CONTRACT_SQL_BEGINNING;
            } else if (tableName.equals(TableConst.CRM_Product)) {
                result = SqlConst.PRODUCT_SQL_BEGINNING;
            } else {
                result = SqlConst.CUSTOMER_SQL_BEGINNING;
            }
            return result;
        }
        
        public static String filterQuery(String columnName){
            if (columnName.equals("type") || columnName.equals("code")) {
                return columnName + StringPool.UNDERLINE;
            } else {
                return columnName;
            }
        }
        
        //private static Log _log = LogFactoryUtil.getLog(SQLUtil.class);

    }
    上述红色部分就是相应的代码部分,这个部分的代码,意思是找到所有的id,我们可以根据这个id找到这个实体的对象,就找到相应的数据了。

    其次我们需要在我们的项目中写上一个按照sql语句查询的方法,这个是我们自己定义的,因为在liferay中,我们只能定义一些基本的增加修改和删除,在service.xml中我们是不能

    做模糊查询的,里面定义的finder全部是精确查询。

    我们首先应该在service.persistence这个包中写上一个你要查询的实体的类XXFinderImpl然后继承BasePersistenceImpl实现XXFinder接口比如:

    package com.ebizwindow.operator.service.persistence;

    import java.util.List;

    import com.ebizwindow.operator.model.Operator;
    import com.liferay.portal.kernel.dao.orm.Query;
    import com.liferay.portal.kernel.dao.orm.QueryUtil;
    import com.liferay.portal.kernel.dao.orm.SQLQuery;
    import com.liferay.portal.kernel.dao.orm.Session;
    import com.liferay.portal.kernel.exception.SystemException;
    import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;

    public class OperatorFinderImpl extends BasePersistenceImpl<Operator> implements OperatorFinder{

        //自己定义的查询的方法。
        public List<Long> findBySQLQueryString(String queryString, int start,
                int end) throws SystemException {
        
            List<Long> list = null;
            if (list == null) {
                Session session = null;
                try {
                    session = openSession();
                    SQLQuery q = session.createSQLQuery(queryString);
                    list = (List<Long>) QueryUtil.list(q, getDialect(), start, end);
                } catch (Exception e) {
                    throw new SystemException(e);
                } finally {
                    closeSession(session);
                }
            }
            
            return list;
        }
        
        //自己定义的HQL查询的方法
        //传过来的用户的条件是,操作员的name,和role,分页查询的方法
        public List<Operator> findOperators(String queryString,int start,int end,String name,String role) throws SystemException{
            List<Operator> list = null;
            
            if (list == null) {
                Session session = null;
                try{
                    session = openSession();
                    Query query = session.createQuery(queryString);
                    query.setString(0, name);
                    query.setString(1, role);
                    list = (List) QueryUtil.list(query, getDialect(), start, end);
                    
                }catch(Exception e){
                    throw new SystemException(e);
                }finally{
                    closeSession(session);
                }
            }
            return list;
        }
     
    }

    然后我们就在portlet中写上自己的实现就行了,比如:

    else if(actionName.equals("operator.search")) {//查询的方法
                        //得到界面上传过来的值
                        String name = ParamUtil.getString(actionRequest, "customer_name",StringPool.BLANK);
                        //select * from operator_operator as operator where operator.roleId in
                        //(select roleId from operator_role where roleName like "%员%" ) and operator.name like "%张妍妍%";
                        String role = ParamUtil.getString(actionRequest, "customer_role",StringPool.BLANK);
                        //得到所在的部门
                        long departmentId = ParamUtil.getLong(actionRequest, "departmentId", 0L);
                        
                        //根据id,用逗号隔开select roleId from operator_role where roleName like "%员%";
                        String idsql = "select roleId from OPERATOR_Role where roleName like '%" + role + "%'";
                        
                        List<Long> ids = OperatorLocalServiceUtil.searchBySQLQueryString(idsql, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
                        String strsql = ids.toString();
                        String ss = StringPool.OPEN_PARENTHESIS + strsql.subSequence(1, strsql.length() - 1)+ StringPool.CLOSE_PARENTHESIS;
                        
                        StringBuffer query = new StringBuffer();
                        query.append("select operator.operatorId from ");
                        query.append(TableConst.OPERATOR_Operator);
                        query.append(" as operator ");
                        query.append(" where 1=1 ");
                        
                        if (!"".equals(role) &&!ss.equals("()")) {
                            query.append(" and ");
                            query.append(" operator.roleId in ");
                            query.append(ss);
                        }
                        if (!"".equals(name)) {
                            query.append(" and ");
                            query.append("operator.name ");
                            query.append(" like '%");
                            query.append(name);
                            query.append("%'");
                        }
                        
                        if (departmentId != 0) {
                            
                            List<Operator> alloperator =  getOperatorByDepartmentId(departmentId);
                            
                            String operatorids = "(";
                            
                            for (int i = 0;i<alloperator.size();i++) {
                                operatorids+=alloperator.get(i).getOperatorId();
                                if (i != alloperator.size()-1) {
                                    operatorids+=",";
                                }
                                
                                
                            }
                            operatorids+=")";
                            
                            
                            query.append(" and ");
                            query.append(" operator.operatorId in ");
                            query.append(operatorids);
                        }
                        
                        listOperator(actionRequest,query.toString());
                        
                        //这个地方就是把前台传过来的name,role传给界面上显示出来。
                        
                        actionRequest.setAttribute("customer_name", name);
                        actionRequest.setAttribute("customer_role", role);
                        
                        forward = "/jsp/operator/operator-list.jsp";

    //根据sql语句查找数据
        private void listOperator(PortletRequest portletRequest,String query) throws PortalException, SystemException {
            
            List<Long> operatorIds = OperatorLocalServiceUtil.searchBySQLQueryString(query, QueryUtil.ALL_POS, QueryUtil.ALL_POS);//查找所有的
            
            List<Operator> operators = new ArrayList<Operator>();
            
            for (int i = 0;i<operatorIds.size();i++) {
                Long operatorId = Long.valueOf(String.valueOf(operatorIds.get(i)));
                Operator operator = OperatorLocalServiceUtil.getOperator(operatorId);
                operators.add(operator);
                
            }
        
            portletRequest.setAttribute("operators", operators);
            
        }

    好吧!后台代码已经写成了,在界面上我们需要定义自己的路径然后找到这个地址。

        function search(){
            var url ='<%=searchCustomerURL %>';
            var customerName = $("input[name='customer_name']").val();
            var customerRole = $("input[name='customer_role']").val();
            $.get(url, {customer_name:customerName,customer_role:customerRole}, function(response) {
                if (response.length > 0) {
                    //$('#<portlet:namespace/>reportTips').html(treeNode.name);
                    $('#<portlet:namespace/>reportListBox').empty().html(response);
                }
            });
            
            
        }

    <portlet:actionURL var="searchCustomerURL" windowState="<%=LiferayWindowState.EXCLUSIVE.toString() %>">
            <portlet:param name="operation" value="operator.search"/>
            <portlet:param name="departmentId" value="<%=String.valueOf(departmentId) %>"/>
        </portlet:actionURL>


        <div class="list-wrapper">
            <div id="searchCustomer" align="right">
                姓名&nbsp;<input class="" id="aui_3_4_0_1_2004" name="customer_name" id = "customer_name" type="text" value="<%=name %>">
                角色&nbsp;<input class="" id="aui_3_4_0_1_1962" name="customer_role" id = "customer_role" type="text" value = "<%=roleName %>">
                <input value="搜索" type="button" onclick="search();">
            </div>

    很简单的查询就实现了

  • 相关阅读:
    解决移动端页面在苹果端滑不到底部的问题
    js点击事件在苹果端失效的问题
    小程序开发基本步骤
    css多行文本省略号(...)
    js判断pc端和移动端的方法
    主流浏览器css兼容问题的总结
    让ie6对png透明图片支持起来
    ajax的探究与使用
    css3实现逐渐变大的圆填充div背景的效果
    js中setTimeout()时间参数设置为0的探讨
  • 原文地址:https://www.cnblogs.com/airycode/p/4910309.html
Copyright © 2011-2022 走看看