Example usage for org.hibernate Query getQueryString

List of usage examples for org.hibernate Query getQueryString

Introduction

In this page you can find the example usage for org.hibernate Query getQueryString.

Prototype

String getQueryString();

Source Link

Document

Get the query string.

Usage

From source file:com.duroty.application.files.manager.FilesManager.java

License:Open Source License

/**
 * DOCUMENT ME!//from   ww  w.  j  a  v  a 2  s .  c  om
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param folderName DOCUMENT ME!
 * @param page DOCUMENT ME!
 * @param messagesByPage DOCUMENT ME!
 * @param order DOCUMENT ME!
 * @param orderType DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws FilesException DOCUMENT ME!
 */
public Vector getFiles(Session hsession, String repositoryName, String folderName, int label, int page,
        int messagesByPage, int order, String orderType) throws FilesException {
    Vector files = new Vector();

    try {
        Users user = getUser(hsession, repositoryName);
        Locale locale = new Locale(user.getUseLanguage());
        TimeZone timeZone = TimeZone.getDefault();

        Date now = new Date();
        Calendar calendar = Calendar.getInstance(timeZone, locale);
        calendar.setTime(now);

        SimpleDateFormat formatter1 = new SimpleDateFormat("MMM dd", locale);
        SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss", locale);
        SimpleDateFormat formatter3 = new SimpleDateFormat("MM/yy", locale);

        Query hquery = null;

        String[] folderNameList = new String[0];

        try {
            folderName = parseFolder(folderName);

            folderNameList = new String[] { folderName };

            if (folderName.equals(this.folderAll) || folderName.equals(this.folderHidden)) {
                folderNameList = new String[] { this.folderAll, this.folderDraft, this.folderHidden,
                        this.folderImportant, this.folderInbox, this.folderSent };
            }
        } catch (Exception ex) {
        }

        if ((folderNameList.length == 0) && (label <= 0)) {
            hquery = hsession.getNamedQuery("attachments");
        } else if ((folderNameList.length > 0) && (label <= 0)) {
            hquery = hsession.getNamedQuery("attachments-by-folder");
        } else if ((folderNameList.length == 0) && (label > 0)) {
            hquery = hsession.getNamedQuery("attachments-by-label");
        } else if ((folderNameList.length > 0) && (label > 0)) {
            hquery = hsession.getNamedQuery("attachments-by-folder-label");
        }

        String aux = hquery.getQueryString();

        switch (order) {
        case ORDER_BY_SIZE:

            if (orderType.equals("ASC")) {
                aux += " order by att_size asc";
            } else {
                aux += " order by att_size desc";
            }

            break;

        case ORDER_BY_DATE:

            if (orderType.equals("ASC")) {
                aux += " order by mes_date asc";
            } else {
                aux += " order by mes_date desc";
            }

            break;

        case ORDER_BY_TYPE:

            if (orderType.equals("ASC")) {
                aux += " order by att_content_type asc";
            } else {
                aux += " order by att_content_type desc";
            }

            break;

        default:

            if (!orderType.equals("ASC")) {
                aux += " order by att_name desc";
            } else {
                aux += " order by att_name asc";
            }

            break;
        }

        SQLQuery h2query = hsession.createSQLQuery(aux);

        if ((folderNameList.length == 0) && (label <= 0)) {
            h2query.setParameterList("no_boxes",
                    new String[] { this.folderTrash, this.folderChat, this.folderSpam, FOLDER_DELETE });
            h2query.setInteger("user", getUser(hsession, repositoryName).getUseIdint());
        } else if ((folderNameList.length > 0) && (label <= 0)) {
            h2query.setParameterList("boxes", folderNameList);
            h2query.setInteger("user", getUser(hsession, repositoryName).getUseIdint());
        } else if ((folderNameList.length == 0) && (label > 0)) {
            h2query.setInteger("label", label);
            h2query.setParameterList("no_boxes",
                    new String[] { this.folderTrash, this.folderChat, this.folderSpam, FOLDER_DELETE });
            h2query.setInteger("user", getUser(hsession, repositoryName).getUseIdint());
        } else if ((folderNameList.length > 0) && (label > 0)) {
            h2query.setInteger("label", label);
            h2query.setParameterList("boxes", folderNameList);
            h2query.setInteger("user", getUser(hsession, repositoryName).getUseIdint());
        }

        h2query.setFirstResult(page * messagesByPage);
        h2query.setMaxResults(messagesByPage);

        h2query.addEntity("testo", AttachmentWithDate.class);

        ScrollableResults scroll = h2query.scroll();

        while (scroll.next()) {
            AttachmentWithDate attachment = (AttachmentWithDate) scroll.get(0);

            AttachmentObj obj = new AttachmentObj();
            obj.setContentType(attachment.getAttContentType());

            Date date = attachment.getAttDate();

            if (date != null) {
                Calendar calendar2 = Calendar.getInstance(timeZone, locale);
                calendar2.setTime(date);

                if ((calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR))
                        && (calendar.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH))
                        && (calendar.get(Calendar.DATE) == calendar2.get(Calendar.DATE))) {
                    obj.setDateStr(formatter2.format(calendar2.getTime()));
                } else if (calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) {
                    obj.setDateStr(formatter1.format(calendar2.getTime()));
                } else {
                    obj.setDateStr(formatter3.format(calendar2.getTime()));
                }
            }

            obj.setDate(date);

            obj.setDate(date);
            obj.setIdint(attachment.getAttIdint());
            obj.setName(attachment.getAttName());
            obj.setPart(attachment.getAttPart());

            int size = attachment.getAttSize();
            size /= 1024;

            if (size > 1024) {
                size /= 1024;
                obj.setSize(size + " MB");
            } else {
                obj.setSize(((size > 0) ? (size + "") : "<1") + " kB");
            }

            String extension = (String) this.extensions.get(attachment.getAttContentType());

            if (StringUtils.isBlank(extension)) {
                extension = "generic";
            }

            obj.setExtension(extension);

            Message message = attachment.getMessage();

            if (message.isMesFlagged()) {
                obj.setFlagged(true);
            } else {
                obj.setFlagged(false);
            }

            if (message.getLabMeses() != null) {
                Iterator it = message.getLabMeses().iterator();
                StringBuffer lab = new StringBuffer();

                while (it.hasNext()) {
                    if (lab.length() > 0) {
                        lab.append(", ");
                    }

                    LabMes labMes = (LabMes) it.next();
                    lab.append(labMes.getId().getLabel().getLabName());
                }

                if (lab.length() > 0) {
                    obj.setLabel(lab.toString());
                } else {
                }
            }

            obj.setBox(message.getMesBox());

            obj.setMid(message.getMesName());

            files.addElement(obj);
        }

        return files;
    } catch (Exception e) {
        throw new FilesException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.mail.manager.MailManager.java

License:Open Source License

/**
 * DOCUMENT ME!// www  .  ja v  a 2  s  .  c  om
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param label DOCUMENT ME!
 * @param page DOCUMENT ME!
 * @param messagesByPage DOCUMENT ME!
 * @param order DOCUMENT ME!
 * @param orderType DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public Vector getMessages(Session hsession, String repositoryName, Label label, int page, int messagesByPage,
        int order, String orderType) throws MailException {
    Vector messages = new Vector();

    try {
        Users user = getUser(hsession, repositoryName);
        Locale locale = new Locale(user.getUseLanguage());
        TimeZone timeZone = TimeZone.getDefault();

        Date now = new Date();
        Calendar calendar = Calendar.getInstance(timeZone, locale);
        calendar.setTime(now);

        SimpleDateFormat formatter1 = new SimpleDateFormat("MMM dd", locale);
        SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss", locale);
        SimpleDateFormat formatter3 = new SimpleDateFormat("MM/yy", locale);

        Query hquery = hsession.getNamedQuery("messages-by-label");
        String aux = hquery.getQueryString();

        switch (order) {
        case ORDER_BY_IMPORTANT:

            if (orderType.equals("ASC")) {
                aux += " order by mes_flagged asc";
            } else {
                aux += " order by mes_flagged desc";
            }

            break;

        case ORDER_BY_ADDRESS:

            if (orderType.equals("ASC")) {
                aux += " order by mes_from asc";
            } else {
                aux += " order by mes_from desc";
            }

            break;

        case ORDER_BY_SIZE:

            if (orderType.equals("ASC")) {
                aux += " order by mes_size asc";
            } else {
                aux += " order by mes_size desc";
            }

            break;

        case ORDER_BY_SUBJECT:

            if (orderType.equals("ASC")) {
                aux += " order by mes_subject asc";
            } else {
                aux += " order by mes_subject desc";
            }

            break;

        case ORDER_BY_DATE:

            if (orderType.equals("ASC")) {
                aux += " order by mes_date asc";
            } else {
                aux += " order by mes_date desc";
            }

            break;

        case ORDER_BY_UNREAD:

            if (orderType.equals("ASC")) {
                aux += " order by mes_recent asc";
            } else {
                aux += " order by mes_recent desc";
            }

            break;

        default:
            aux += " order by mes_date desc";

            break;
        }

        SQLQuery h2query = hsession.createSQLQuery(aux);
        h2query.addEntity("i", Message.class);
        h2query.setInteger("label", label.getLabIdint());
        h2query.setInteger("user", user.getUseIdint());
        h2query.setString("folderTrash", this.folderTrash);
        h2query.setString("folderSpam", this.folderSpam);
        h2query.setString("folderDelete", FOLDER_DELETE);
        h2query.setFirstResult(page * messagesByPage);
        h2query.setMaxResults(messagesByPage);

        ScrollableResults scroll = h2query.scroll();

        while (scroll.next()) {
            Message message = (Message) scroll.get(0);

            MessageObj obj = new MessageObj(message.getMesName());

            obj.setBox(message.getMesBox());

            obj.setFrom(message.getMesFrom());

            if ((message.getAttachments() != null) && (message.getAttachments().size() > 0)) {
                obj.setHasAttachment(true);
            } else {
                obj.setHasAttachment(false);
            }

            int size = message.getMesSize();
            size /= 1024;

            if (size > 1024) {
                size /= 1024;
                obj.setSize(size + " MB");
            } else {
                obj.setSize(((size > 0) ? (size + "") : "<1") + " kB");
            }

            if (message.getMesBox().equals(folderSent)) {
                try {
                    obj.setEmail(message.getMesTo());
                } catch (Exception e) {
                    obj.setEmail("unknown to");
                }
            } else {
                obj.setEmail(message.getMesFrom());
            }

            Date date = message.getMesDate();

            if (date != null) {
                Calendar calendar2 = Calendar.getInstance(timeZone, locale);
                calendar2.setTime(date);

                if ((calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR))
                        && (calendar.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH))
                        && (calendar.get(Calendar.DATE) == calendar2.get(Calendar.DATE))) {
                    obj.setDateStr(formatter2.format(calendar2.getTime()));
                } else if (calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) {
                    obj.setDateStr(formatter1.format(calendar2.getTime()));
                } else {
                    obj.setDateStr(formatter3.format(calendar2.getTime()));
                }
            }

            obj.setDate(date);

            if (message.getLabMeses() != null) {
                Iterator it = message.getLabMeses().iterator();
                StringBuffer buff = new StringBuffer();

                while (it.hasNext()) {
                    if (buff.length() > 0) {
                        buff.append(", ");
                    }

                    LabMes labMes = (LabMes) it.next();
                    buff.append(labMes.getId().getLabel().getLabName());
                }

                obj.setLabel(buff.toString());
            }

            try {
                if (StringUtils.isBlank(message.getMesSubject())) {
                    obj.setSubject("(no subject)");
                } else {
                    obj.setSubject(message.getMesSubject());
                }
            } catch (Exception ex) {
                obj.setSubject("(no subject)");
            }

            if (message.isMesFlagged()) {
                obj.setFlagged(true);
            } else {
                obj.setFlagged(false);
            }

            if (message.isMesRecent()) {
                obj.setRecent(true);
            } else {
                obj.setRecent(false);
            }

            String priority = "normal";

            if (MessageUtilities.isHighPriority(message.getMesHeaders())) {
                priority = "high";
            } else if (MessageUtilities.isLowPriority(message.getMesHeaders())) {
                priority = "low";
            }

            obj.setPriority(priority);

            messages.addElement(obj);
        }

        return messages;
    } catch (Exception e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.ejushang.steward.common.genericdao.dao.hibernate.GeneralDAO.java

License:Apache License

/**
 * hql/*from   www. j  a va2  s. c o  m*/
 * @param ql
 * @param page ?null
 * @param queryPrepare ?query?,?null
 * @param args
 * @param <RT>
 * @return
 */
public <RT> List<RT> queryWithPrepare(String ql, Page page, QueryPrepare queryPrepare, Object... args) {
    Query query = getSession().createQuery(ql);
    for (int i = 0; i < args.length; i++) {
        query.setParameter(i, args[i]);
    }
    if (queryPrepare != null) {
        queryPrepare.prepare(query);
    }
    if (page == null) {
        return query.list();
    }

    if (this.hasGroupBy(ql)) {
        //count
        StringBuilder countQL = new StringBuilder("select count(1) ");
        countQL.append(ql.substring(ql.indexOf("from"), ql.lastIndexOf("order")));
        countQL = new StringBuilder(removeFetchInCountQl(countQL.toString()));
        Query countQuery = getSession().createQuery(countQL.toString());
        for (int i = 0; i < args.length; i++) {
            countQuery.setParameter(i, args[i]);
        }
        List count = countQuery.list();
        page.setTotalCount(count.size());

    } else {
        //count
        page.setTotalCount(this.count(query.getQueryString(), args));
    }

    query.setFirstResult(page.getStart());
    query.setMaxResults(page.getLimit());
    page.setResult(query.list());
    return page.getResult();
}

From source file:com.ejushang.uams.server.common.genericdao.dao.hibernate.GeneralDAO.java

License:Apache License

/**
 * hql/*from ww w .ja v  a 2 s .  c o  m*/
 * @param ql
 * @param page ?null
 * @param args
 * @param <RT>
 * @return
 */
public <RT> List<RT> query(String ql, Page page, Object... args) {
    Query query = getSession().createQuery(ql);
    for (int i = 0; i < args.length; i++) {
        query.setParameter(i, args[i]);
    }
    if (page == null) {
        return query.list();
    }

    if (this.hasGroupBy(ql)) {
        //count
        StringBuilder countQL = new StringBuilder("select count(*) ");
        countQL.append(ql.substring(ql.indexOf("from"), ql.lastIndexOf("order")));
        Query countQuery = getSession().createQuery(countQL.toString());
        for (int i = 0; i < args.length; i++) {
            countQuery.setParameter(i, args[i]);
        }
        List count = countQuery.list();
        page.setTotalCount(count.size());

    } else {
        //count
        page.setTotalCount(this.count(query.getQueryString(), args));
    }

    query.setFirstResult(page.getStart());
    query.setMaxResults(page.getLimit());
    page.setResult(query.list());
    return page.getResult();
}

From source file:com.europabrewing.util.HibernateUtil.java

License:Open Source License

/**
 * Print all data that is held in this database
 *
 * @throws org.hibernate.HibernateException
 *//*  www.j a va 2  s .  com*/
public static void printAllData() throws HibernateException {
    Session session = getSession();

    try {
        System.out.println("querying all the managed entities...");

        final Map<String, ClassMetadata> metadataMap = session.getSessionFactory().getAllClassMetadata();

        for (String key : metadataMap.keySet()) {
            final ClassMetadata classMetadata = metadataMap.get(key);
            final String entityName = classMetadata.getEntityName();
            final Query query = session.createQuery("from " + entityName);

            System.out.println("executing: " + query.getQueryString());
            for (Object o : query.list()) {
                System.out.println("  " + o);
            }
        }

    } finally {
        session.close();
    }
}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java

License:Apache License

public RepositoryQueryDiagResponse executeQueryDiagnosticsRequest(RepositoryQueryDiagRequest request,
        OperationResult result) {/*w  ww  . j  a  va2 s. c  o m*/
    LOGGER_PERFORMANCE.debug("> execute query diagnostics {}", request);

    Session session = null;
    try {
        session = baseHelper.beginReadOnlyTransaction(); // beware, not all databases support read-only transactions!

        final String implementationLevelQuery;
        final Map<String, RepositoryQueryDiagResponse.ParameterValue> implementationLevelQueryParameters;
        final Query query;
        final boolean isMidpointQuery = request.getImplementationLevelQuery() == null;
        if (isMidpointQuery) {
            QueryEngine2 engine = new QueryEngine2(getConfiguration(), prismContext);
            RQueryImpl rQuery = (RQueryImpl) engine.interpret(request.getQuery(), request.getType(), null,
                    false, session);
            query = rQuery.getQuery();
            implementationLevelQuery = query.getQueryString();
            implementationLevelQueryParameters = new HashMap<>();
            for (Map.Entry<String, QueryParameterValue> entry : rQuery.getQuerySource().getParameters()
                    .entrySet()) {
                implementationLevelQueryParameters.put(entry.getKey(),
                        new RepositoryQueryDiagResponse.ParameterValue(entry.getValue().getValue(),
                                entry.getValue().toString()));
            }
        } else {
            implementationLevelQuery = (String) request.getImplementationLevelQuery();
            implementationLevelQueryParameters = new HashMap<>();
            query = session.createQuery(implementationLevelQuery);
        }

        List<?> objects = request.isTranslateOnly() ? null : query.list();
        if (isMidpointQuery && objects != null) {
            // raw GetObjectResult instances are useless outside repo-sql-impl module, so we'll convert them to objects
            @SuppressWarnings("unchecked")
            List<GetObjectResult> listOfGetObjectResults = (List<GetObjectResult>) objects;
            objects = queryResultToPrismObjects(listOfGetObjectResults, request.getType(), null, null, session,
                    result);
        }

        RepositoryQueryDiagResponse response = new RepositoryQueryDiagResponse(objects,
                implementationLevelQuery, implementationLevelQueryParameters);
        session.getTransaction().rollback();
        return response;
    } catch (SchemaException | QueryException | RuntimeException ex) {
        baseHelper.handleGeneralException(ex, session, result);
        throw new IllegalStateException("shouldn't get here");
    } finally {
        baseHelper.cleanupSessionAndResult(session, result);
    }
}

From source file:com.hp.j2sh.project.action.AuthenticateLogin.java

@Override
public String execute() throws Exception {
    Session session = MyHibernateUtil.getSession();
    Criteria criteria = session.createCriteria(AllUsers.class);
    Criterion usernameCriterion = Restrictions.eq("username", username);
    Criterion passwordCriterion = Restrictions.eq("password", password);
    criteria.add(Restrictions.and(usernameCriterion, passwordCriterion));
    AllUsers user = (AllUsers) criteria.uniqueResult();
    if (user != null) {
        System.out.println("user_id : " + user.getUserId());
        sessionMap.put("user_id", user.getUserId());
        System.out.println("user_id : " + (Integer) sessionMap.get("user_id"));

        Query query = session.createQuery("FROM CommunityUsers c WHERE c.userId = ?");
        query.setParameter(0, user.getUserId());
        System.out.println("query :: " + query.getQueryString());
        List<CommunityUsers> tempList = query.list();
        List<AllCommunities> listUser = new ArrayList<AllCommunities>();
        for (CommunityUsers communityUsers : tempList) {
            Criteria criteria2 = session.createCriteria(AllCommunities.class);
            criteria2.add(Restrictions.eq("communityId", communityUsers.getCommunityId()));
            AllCommunities allCommunities = (AllCommunities) criteria2.uniqueResult();
            listUser.add(allCommunities);
        }/*from   w w  w  .j av  a  2 s .c  o m*/
        sessionMap.put("communityListUser", listUser);

        List<AllCommunities> listAll = new ArrayList<AllCommunities>();
        List<Integer> userIds = new ArrayList<Integer>();
        for (AllCommunities allCommunities : listUser) {
            userIds.add(allCommunities.getCommunityId());
        }
        System.out.println("userIDs :: " + userIds);
        Criteria criteria1 = session.createCriteria(AllCommunities.class);
        ArrayList<AllCommunities> tempListAll = (ArrayList<AllCommunities>) criteria1.list();
        for (AllCommunities ac : tempListAll) {
            boolean found = false;
            for (Integer i : userIds) {
                if (ac.getCommunityId().equals(i)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                listAll.add(ac);
            }
        }
        sessionMap.put("communityListAll", listAll);
        return SUCCESS;
    } else {
        sessionMap.put("loginErrorMessage", "Invalid username and/or password!");
        return INPUT;
    }
}

From source file:com.hp.j2sh.project.action.JoinCommunity.java

@Override
public String execute() throws Exception {
    try {/* ww w .j  a  v  a  2 s  .c om*/
        Integer community_id = Integer.parseInt(communityId);
        Integer user = (Integer) sessionMap.get("user_id");
        System.out.println("Join :: " + community_id);
        System.out.println("user :: " + user);

        Session session = MyHibernateUtil.getSession();
        Transaction transaction = session.beginTransaction();

        CommunityUsers communityUsers = new CommunityUsers(community_id, (Integer) sessionMap.get("user_id"));

        session.save(communityUsers);
        transaction.commit();

        sessionMap.put("RegisterMessage", "Community successfully joined !!!");

        try {
            Query query = session.createQuery("FROM CommunityUsers c WHERE c.userId = :user");
            query.setInteger("user", user);
            System.out.println("query :: " + query.getQueryString());
            List<CommunityUsers> tempList = query.list();
            List<AllCommunities> listUser = new ArrayList<AllCommunities>();
            for (CommunityUsers communityUsers1 : tempList) {
                Criteria criteria2 = session.createCriteria(AllCommunities.class);
                criteria2.add(Restrictions.eq("communityId", communityUsers1.getCommunityId()));
                AllCommunities allCommunities1 = (AllCommunities) criteria2.list().iterator().next();
                listUser.add(allCommunities1);
            }
            sessionMap.put("communityListUser", listUser);

            List<AllCommunities> listAll = new ArrayList<AllCommunities>();
            List<Integer> userIds = new ArrayList<Integer>();
            for (AllCommunities allCommunities1 : listUser) {
                userIds.add(allCommunities1.getCommunityId());
            }
            System.out.println("userIDs :: " + userIds);
            Criteria criteria1 = session.createCriteria(AllCommunities.class);
            List<AllCommunities> tempListAll = criteria1.list();
            for (AllCommunities ac : tempListAll) {
                boolean found = false;
                for (Integer i : userIds) {
                    if (ac.getCommunityId().equals(i)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    listAll.add(ac);
                }
            }
            sessionMap.put("communityListAll", listAll);
        } catch (Exception e) {
            System.out.println("Join :: query :: " + e);
        }
        return SUCCESS;
    } finally {

    }
    //        catch (Exception e) {
    //            System.out.println("( JoinCommunity ) Exception :: " + e);
    //            sessionMap.put("RegisterMessage", "Community joining unsuccessful !!!");
    //            return ERROR;
    //        }
}

From source file:com.hp.j2sh.project.action.RegisterCommunity.java

@Override
public String execute() throws Exception {
    try {//from  w  w w.  java2s.com
        Integer user_id = (Integer) sessionMap.get("user_id");
        Session session = MyHibernateUtil.getSession();
        Transaction transaction = session.beginTransaction();

        Query query = session.createQuery("FROM AllUsers a WHERE a.userId = :userID");
        query.setInteger("userID", user_id);
        AllUsers allUsers = (AllUsers) query.uniqueResult();

        AllCommunities allCommunities = new AllCommunities(community_name, user_id);
        allCommunities.setAllUsers(allUsers);
        allUsers.getAllCommunities().add(allCommunities);

        session.save(allCommunities);
        session.save(allUsers);
        transaction.commit();

        sessionMap.put("RegisterMessage", "Community Creation Successful !!!");

        query = session.createQuery("FROM CommunityUsers c WHERE c.userId = ?");
        query.setInteger(0, (Integer) sessionMap.get("user_id"));
        System.out.println("query :: " + query.getQueryString());
        List<CommunityUsers> tempList = query.list();
        List<AllCommunities> listUser = new ArrayList<AllCommunities>();
        for (CommunityUsers communityUsers1 : tempList) {
            Criteria criteria2 = session.createCriteria(AllCommunities.class);
            criteria2.add(Restrictions.eq("communityId", communityUsers1.getCommunityId()));
            AllCommunities allCommunities1 = (AllCommunities) criteria2.uniqueResult();
            listUser.add(allCommunities1);
        }
        sessionMap.put("communityListUser", listUser);

        List<AllCommunities> listAll = new ArrayList<AllCommunities>();
        List<Integer> userIds = new ArrayList<Integer>();
        for (AllCommunities allCommunities1 : listUser) {
            userIds.add(allCommunities1.getCommunityId());
        }
        System.out.println("userIDs :: " + userIds);
        Criteria criteria1 = session.createCriteria(AllCommunities.class);
        List<AllCommunities> tempListAll = criteria1.list();
        for (AllCommunities ac : tempListAll) {
            boolean found = false;
            for (Integer i : userIds) {
                if (ac.getCommunityId().equals(i)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                listAll.add(ac);
            }
        }
        sessionMap.put("communityListAll", listAll);
        return SUCCESS;
    } catch (Exception e) {
        System.out.println("( RegisterCommunity ) Exception :: " + e);
    }
    sessionMap.put("RegisterMessage", "Community Creation Failed !!!");
    return ERROR;
}

From source file:com.hp.j2sh.project.action.RegisterUser.java

@Override
public String execute() throws Exception {
    try {// w ww. j  a  va2  s.c  o  m

        if (gender.equalsIgnoreCase("male")) {
            gender = "M";
        } else if (gender.equalsIgnoreCase("female")) {
            gender = "F";
        } else {
            gender = "O";
        }

        Session session = MyHibernateUtil.getSession();
        Transaction transaction = session.beginTransaction();

        Date dob = new Date(
                yearMillis * (year_dob - 1970) + monthMillis * (month_dob - 1) + dayMillis * (day_dob));
        AllUsers allUsers = new AllUsers(username, password);
        UserEducationalDetails userEducationalDetails = new UserEducationalDetails(cur_institution, degree,
                major, degree_comp);
        UserPersonalDetails userPersonalDetails = new UserPersonalDetails(fname, mname, lname, p_email, s_email,
                p_contact, s_contact, dob, gender);
        UserOtherDetails userOtherDetails = new UserOtherDetails(hometown, address1, address2, address3,
                address4);
        UserWorkDetails userWorkDetails = new UserWorkDetails(work_organization, work_position, work_since);
        userEducationalDetails.setAllUsers(allUsers);
        userOtherDetails.setAllUsers(allUsers);
        userPersonalDetails.setAllUsers(allUsers);
        userWorkDetails.setAllUsers(allUsers);
        allUsers.setUserEducationalDetails(userEducationalDetails);
        allUsers.setUserOtherDetails(userOtherDetails);
        allUsers.setUserPersonalDetails(userPersonalDetails);
        allUsers.setUserWorkDetails(userWorkDetails);

        session.save(allUsers);
        transaction.commit();

        sessionMap.put("RegisterMessage", "User Registration Successfull !!!");
        sessionMap.put("user_id", allUsers.getUserId());

        Query query = session.createQuery("FROM CommunityUsers c WHERE c.userId = ?");
        query.setParameter(0, sessionMap.get("user_id"));
        System.out.println("query :: " + query.getQueryString());
        List<CommunityUsers> tempList = query.list();
        List<AllCommunities> listUser = new ArrayList<AllCommunities>();
        for (CommunityUsers communityUsers : tempList) {
            Criteria criteria2 = session.createCriteria(AllCommunities.class);
            criteria2.add(Restrictions.eq("communityId", communityUsers.getCommunityId()));
            AllCommunities allCommunities = (AllCommunities) criteria2.uniqueResult();
            listUser.add(allCommunities);
        }
        sessionMap.put("communityListUser", listUser);

        List<AllCommunities> listAll = new ArrayList<AllCommunities>();
        List<Integer> userIds = new ArrayList<Integer>();
        for (AllCommunities allCommunities : listUser) {
            userIds.add(allCommunities.getCommunityId());
        }
        System.out.println("userIDs :: " + userIds);
        Criteria criteria1 = session.createCriteria(AllCommunities.class);
        ArrayList<AllCommunities> tempListAll = (ArrayList<AllCommunities>) criteria1.list();
        for (AllCommunities ac : tempListAll) {
            boolean found = false;
            for (Integer i : userIds) {
                if (ac.getCommunityId().equals(i)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                listAll.add(ac);
            }
        }
        sessionMap.put("communityListAll", listAll);

        return SUCCESS;
    } catch (Exception e) {
        System.out.println("( RegisterUser ) Exception :: " + e);
    }
    sessionMap.put("RegisterMessage", "User Registration Failed !!!");
    return ERROR;
}