Example usage for org.hibernate Criteria createAlias

List of usage examples for org.hibernate Criteria createAlias

Introduction

In this page you can find the example usage for org.hibernate Criteria createAlias.

Prototype

public Criteria createAlias(String associationPath, String alias) throws HibernateException;

Source Link

Document

Join an association, assigning an alias to the joined association.

Usage

From source file:com.court.controller.ReportFormFxmlController.java

@FXML
private void onMemberPayOfficeAction(ActionEvent event) {

    Dialog<Pair<String, Integer>> dialog = new Dialog<>();
    dialog.setTitle("Member List");
    dialog.setHeaderText("Select Payment Office");
    ButtonType viewBtn = new ButtonType("View Report", ButtonData.OK_DONE);
    dialog.getDialogPane().getButtonTypes().addAll(viewBtn, ButtonType.CANCEL);
    GridPane grid = new GridPane();
    grid.setHgap(10);//ww  w .j  a  v a2  s.  c o m
    grid.setVgap(10);
    grid.setPadding(new Insets(20, 150, 10, 10));

    TextField bField = new TextField();
    ComboBox<String> cbox = new ComboBox<>(FXCollections.observableArrayList("All", "Active", "Deactivated"));
    cbox.getSelectionModel().select(0);
    TextFields.bindAutoCompletion(bField, getPaymentOffice());

    grid.add(new Label("Office:"), 0, 0);
    grid.add(bField, 1, 0);
    grid.add(new Label("Member Status:"), 0, 1);
    grid.add(cbox, 1, 1);
    dialog.getDialogPane().setContent(grid);
    dialog.setResultConverter(db -> {
        if (db == viewBtn) {
            return new Pair<>(bField.getText(), cbox.getSelectionModel().getSelectedIndex());
        }
        return null;
    });

    Optional<Pair<String, Integer>> result = dialog.showAndWait();
    result.ifPresent(b -> {
        //  String reportPath = "com/court/reports/MemberReport.jasper";

        String reportPath = null;
        try {
            reportPath = PropHandler.getStringProperty("report_path") + "MemberReport.jasper";
        } catch (IOException ex) {
            Logger.getLogger(ReportFormFxmlController.class.getName()).log(Level.SEVERE, null, ex);
        }

        Session session = HibernateUtil.getSessionFactory().openSession();
        Criteria c = session.createCriteria(Member.class, "m");
        c.createAlias("m.payOffice", "po");
        c.createAlias("m.branch", "b");
        if (!b.getKey().equalsIgnoreCase("All")) {
            c.add(Restrictions.eq("po.branchCode", b.getKey().split("-")[0]));
        }
        switch (b.getValue()) {
        case 1:
            c.add(Restrictions.eq("m.status", true));
            break;
        case 2:
            c.add(Restrictions.eq("m.status", false));
            break;
        }

        c.add(Restrictions.eq("b.status", true));
        List<Member> list = (List<Member>) c.list();
        List<Member> orderedList = list.stream()
                .sorted(Comparator.comparing(p -> p.getBranch().getBranchCode())).collect(Collectors.toList());
        JRBeanCollectionDataSource memberBeanCollection = new JRBeanCollectionDataSource(orderedList);
        Map<String, Object> map = new HashMap<>();
        map.put("companyName", ReportHandler.COMPANY_NAME);
        map.put("companyAddress", ReportHandler.ADDRESS);
        map.put("reportTitle", "Welfare Member List of Payment Office - " + b.getKey().split("-")[1]);
        ReportHandler rh = new ReportHandler(reportPath, map, memberBeanCollection);
        //            rh.genarateReport();
        boolean blah = rh.genReport();
        if (blah) {
            rh.viewReport();
        }
        session.close();
    });
}

From source file:com.court.controller.ReportFormFxmlController.java

@FXML
private void onMemberHistoryAction(ActionEvent event) {

    Dialog<String> dialog = new Dialog<>();
    dialog.setTitle("Member History");
    dialog.setHeaderText("Select Member");
    ButtonType viewBtn = new ButtonType("View Report", ButtonData.OK_DONE);
    dialog.getDialogPane().getButtonTypes().addAll(viewBtn, ButtonType.CANCEL);
    GridPane grid = new GridPane();
    grid.setHgap(10);/*from   w w  w  .j a  va  2s. c o  m*/
    grid.setVgap(10);
    grid.setPadding(new Insets(20, 150, 10, 10));

    TextField bField = new TextField();
    TextFields.bindAutoCompletion(bField, getMembers(false));

    grid.add(new Label("Member:"), 0, 0);
    grid.add(bField, 1, 0);
    dialog.getDialogPane().setContent(grid);
    dialog.setResultConverter(db -> {
        if (db == viewBtn) {
            return bField.getText().split("-")[0];
        }
        return null;
    });

    Optional<String> result = dialog.showAndWait();
    result.ifPresent(mId -> {
        // String reportPath = "com/court/reports/MbrHistoryReport.jasper";
        //String subReportPath_1 = "com/court/reports/MbrHistorySubReport.jasper";
        // String subReportPath_2 = "com/court/reports/MbrHistorySubPaymentsReport.jasper";

        String reportPath = null, subReportPath_1 = null, subReportPath_2 = null;
        try {
            reportPath = PropHandler.getStringProperty("report_path") + "MbrHistoryReport.jasper";
            subReportPath_1 = PropHandler.getStringProperty("report_path") + "MbrHistorySubReport.jasper";
            subReportPath_2 = PropHandler.getStringProperty("report_path")
                    + "MbrHistorySubPaymentsReport.jasper";
        } catch (IOException ex) {
            Logger.getLogger(ReportFormFxmlController.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            JasperReport subReport_1 = (JasperReport) JRLoader.loadObject(new File(subReportPath_1));

            JasperReport subReport_2 = (JasperReport) JRLoader.loadObject(new File(subReportPath_2));

            Session session = HibernateUtil.getSessionFactory().openSession();
            Criteria c = session.createCriteria(Member.class);
            Member filteredM = (Member) c.add(Restrictions.eq("memberId", mId)).uniqueResult();

            System.out.println("DEEPAL - " + filteredM.getMemberLoans().size());

            Criteria c1 = session.createCriteria(SubscriptionPay.class, "sp");
            c1.createAlias("sp.memberSubscriptions", "ms");
            c1.createAlias("ms.member", "m");
            c1.add(Restrictions.eq("m.memberId", mId));
            List<SubscriptionPay> subscriptionPays = c1.list();

            Map<String, Object> map = new HashMap<>();
            map.put("companyName", ReportHandler.COMPANY_NAME);
            map.put("companyAddress", ReportHandler.ADDRESS);
            map.put("SUBREPORT_1", subReport_1);
            map.put("SUBREPORT_2", subReport_2);
            map.put("reportTitle", "Member History");
            map.put("member_id", filteredM.getMemberId());
            map.put("full_name", filteredM.getFullName());
            map.put("nic", filteredM.getNic());
            map.put("emp_id", filteredM.getEmpId());
            map.put("job_title", filteredM.getJobTitle());
            map.put("payment_office", filteredM.getPayOffice().getBranchName());
            map.put("mbr_status", filteredM.isStatus());
            map.put("branch", filteredM.getBranch().getBranchName());
            map.put("member_loans", filteredM.getMemberLoans());
            map.put("member_subpay", subscriptionPays);
            ReportHandler rh = new ReportHandler(reportPath, map, null);
            //                rh.genarateReport();
            boolean blah = rh.genReport();
            if (blah) {
                rh.viewReport();
            }
            session.close();
        } catch (JRException e) {
            e.printStackTrace();
        }

    });
}

From source file:com.court.controller.UserManageFxmlController.java

private int getUHasRoleIdByUserName(Session session, String userName) {
    Criteria c = session.createCriteria(UserHasUserRole.class);
    c.createAlias("user", "u");
    c.add(Restrictions.eq("u.userName", userName));
    UserHasUserRole filteredUser = (UserHasUserRole) c.uniqueResult();
    return filteredUser != null ? filteredUser.getId() : 0;
}

From source file:com.court.controller.UserManageFxmlController.java

private void searchUser(String role, String fullName) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Criteria c = session.createCriteria(UserHasUserRole.class);
    c.createAlias("userRole", "ur").createAlias("user", "u");

    if (!role.isEmpty()) {
        c.add(Restrictions.eq("ur.roleName", role));
    }//from w ww . j  a  va  2  s  .  c om
    if (!fullName.isEmpty()) {
        c.add(Restrictions.eq("u.fullName", fullName));
    }
    List<UserHasUserRole> uhur = c.list();
    initUserTable(FXCollections.observableArrayList(uhur));
}

From source file:com.cristian.tareask.daoImpl.EmailConversationDaoImpl.java

@Override
public List getLastEmailConversation() {
    s = HibernateUtil.getSessionFactory().openSession();
    Criteria c = s.createCriteria(EmailConversation.class, "conversation");
    c.createAlias("conversation.emailMessage", "lastEmail");
    c.addOrder(Order.desc("lastEmail.date"));
    List mails = (List) c.list();
    return mails;
}

From source file:com.cristian.tareask.daoImpl.MessageReceptorDaoImpl.java

@Override
public List getLastMailByUserReceptor(Integer idUser) {
    s = HibernateUtil.getSessionFactory().openSession();
    Criteria c = s.createCriteria(MessageReceptor.class, "receptor");
    c.createAlias("receptor.message", "message");
    c.createAlias("message.conversation", "conversation");
    List mails = (List) c.list();
    return mails;
}

From source file:com.dell.asm.asmcore.asmmanager.db.DeviceInventoryDAO.java

License:Open Source License

/**
 * Retrieve all from Device Inventory.//  ww w  .jav a 2  s . c o m
 *
 * @return list of entities
 */
@SuppressWarnings("unchecked")
public List<DeviceInventoryEntity> getAllDeviceInventory(List<SortParamParser.SortInfo> sortInfos,
        List<FilterParamParser.FilterInfo> filterInfos, PaginationInfo paginationInfo)
        throws AsmManagerDAOException {

    Session session = null;
    Transaction tx = null;
    List<DeviceInventoryEntity> entityList = new ArrayList<DeviceInventoryEntity>();

    try {
        // NOTE[fcarta] need to at this here so we dont nest the session / transaction
        List<String> refIdsServices = ListUtils.EMPTY_LIST;
        List<String> refIdsGroups = ListUtils.EMPTY_LIST;
        List<String> refIdsAllGroups = ListUtils.EMPTY_LIST;

        boolean spFilterSet = false;
        boolean spGlobalFilterSet = false;
        if (CollectionUtils.isNotEmpty(filterInfos)) {
            for (FilterParamParser.FilterInfo filterInfo : filterInfos) {
                // if there is a service filter then grab the ref id for the device
                if (StringUtils.equals(SERVICE_FILTER_PARAM, filterInfo.getColumnName())) {
                    refIdsServices = getRefIdsOfDevicesByDeploymentIds(filterInfo.getColumnValue());
                } else if (StringUtils.equals(SERVERPOOL_FILTER_PARAM, filterInfo.getColumnName())) {
                    if (filterInfo.getColumnValue()
                            .contains(ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_POOL_GLOBAL_ID)) {
                        refIdsAllGroups = getRefIdsOfDevicesByGroupIds(filterInfo.getColumnValue());
                        spGlobalFilterSet = true;
                    } else {
                        refIdsGroups = getRefIdsOfDevicesByGroupIds(filterInfo.getColumnValue());
                        spFilterSet = true;
                    }
                }
            }
        }

        session = _dao._database.getNewSession();
        tx = session.beginTransaction();

        Criteria criteria = session.createCriteria(DeviceInventoryEntity.class);
        if (sortInfos != null) {
            BaseDAO.addSortCriteria(criteria, sortInfos);
        }

        if (filterInfos != null) {
            final List<FilterParamParser.FilterInfo> notFound = BaseDAO.addFilterCriteria(criteria, filterInfos,
                    DeviceInventoryEntity.class);
            if (CollectionUtils.isNotEmpty(notFound)) {

                for (FilterParamParser.FilterInfo filterInfo : notFound) {
                    // if this is a filter by service then we need to get the subset of ref ids for devices
                    // only in the deployment id subset passed
                    if (StringUtils.equals(SERVICE_FILTER_PARAM, filterInfo.getColumnName())) {
                        if (CollectionUtils.isNotEmpty(refIdsServices)) {
                            criteria.add(Restrictions.in("refId", refIdsServices));
                        }
                    } else if (StringUtils.equals(SERVERPOOL_FILTER_PARAM, filterInfo.getColumnName())) {
                        if (spGlobalFilterSet) {
                            if (refIdsAllGroups.isEmpty()) {
                                // this means there are no servers in any server pool - all are in Global
                                criteria.add(Restrictions.sqlRestriction("(1=1)"));
                            } else {
                                criteria.add(Restrictions.not(Restrictions.in("refId", refIdsAllGroups)));
                            }
                        } else if (spFilterSet) {
                            if (refIdsGroups.isEmpty()) {
                                criteria.add(Restrictions.sqlRestriction("(1=0)"));
                            } else {
                                criteria.add(Restrictions.in("refId", refIdsGroups));
                            }
                        }
                    } else {
                        criteria.createAlias("deviceInventoryEntity", "deviceInventoryEntityAlias");
                        criteria.add(Restrictions.eq("deviceInventoryEntityAlias.deviceKey",
                                filterInfo.getColumnName()));
                        if (filterInfo.getColumnValue().size() == 1) {
                            criteria.add(Restrictions.eq("deviceInventoryEntityAlias.deviceValue",
                                    filterInfo.getColumnValue().get(0)));
                        } else if (filterInfo.getColumnValue().size() > 1) {
                            criteria.add(Restrictions.in("deviceInventoryEntityAlias.deviceValue",
                                    filterInfo.getColumnValue()));
                        }
                    }
                }
            }
        }

        if (paginationInfo != null) {
            int offset = paginationInfo.getOffset();
            int limit = paginationInfo.getLimit();
            int pageSize = limit;
            criteria.setFirstResult(offset);
            criteria.setMaxResults(pageSize);
        }

        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

        entityList = criteria.list();
        this.setFirmwareBasedOnDeployment(entityList);
        tx.commit();
    } catch (Exception e) {
        logger.warn("Caught exception during get all devices in inventory: " + e, e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during get all devices: " + ex);
        }
        throw new AsmManagerDAOException("Caught exception during get all devices in inventory: ", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during get all devices: " + ex);
        }
    }

    return entityList;
}

From source file:com.dell.asm.asmcore.asmmanager.db.DeviceInventoryDAO.java

License:Open Source License

/**
 * Helper method to get total number of records with filter parameters
 *
 * @param filterInfos - List for holding filtering information parsed from filter query parameter value
 * @return int - total number of records
 *//*from  ww  w  . ja v  a2s.  c o m*/
public Integer getTotalRecords(List<FilterParamParser.FilterInfo> filterInfos) {
    long totalRecords = 0;
    Session session = null;
    Transaction tx = null;
    try {
        session = _dao._database.getNewSession();
        tx = session.beginTransaction();

        Criteria criteria = session.createCriteria(DeviceInventoryEntity.class);

        final List<FilterParamParser.FilterInfo> notFound = BaseDAO.addFilterCriteria(criteria, filterInfos,
                DeviceInventoryEntity.class);
        if (CollectionUtils.isNotEmpty(notFound)) {

            for (FilterParamParser.FilterInfo filterInfo : notFound) {
                // if this is a filter by service then we need to get the subset of ref ids for devices
                // only in the deployment id subset passed
                if (StringUtils.equals(SERVICE_FILTER_PARAM, filterInfo.getColumnName())) {
                    final List<String> refIds = getRefIdsOfDevicesByDeploymentIds(filterInfo.getColumnValue());
                    criteria.add(Restrictions.in("refId", refIds));
                } else if (StringUtils.equals(SERVERPOOL_FILTER_PARAM, filterInfo.getColumnName())) {
                    if (filterInfo.getColumnValue()
                            .contains(ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_POOL_GLOBAL_ID)) {
                        final List<String> refIds = getRefIdsOfDevicesByGroupIds(filterInfo.getColumnValue());
                        if (refIds.isEmpty()) {
                            criteria.add(Restrictions.sqlRestriction("(1=0)"));
                        } else {
                            criteria.add(Restrictions.not(Restrictions.in("refId", refIds)));
                        }
                    } else {
                        final List<String> refIds = getRefIdsOfDevicesByGroupIds(filterInfo.getColumnValue());
                        if (refIds.isEmpty()) {
                            criteria.add(Restrictions.sqlRestriction("(1=0)"));
                        } else {
                            criteria.add(Restrictions.in("refId", refIds));
                        }
                    }
                } else {
                    criteria.createAlias("deviceInventoryEntity", "deviceInventoryEntityAlias");
                    criteria.add(Restrictions.eq("deviceInventoryEntityAlias.deviceKey",
                            filterInfo.getColumnName()));
                    if (filterInfo.getColumnValue().size() == 1) {
                        criteria.add(Restrictions.eq("deviceInventoryEntityAlias.deviceValue",
                                filterInfo.getColumnValue().get(0)));
                    } else if (filterInfo.getColumnValue().size() > 1) {
                        criteria.add(Restrictions.in("deviceInventoryEntityAlias.deviceValue",
                                filterInfo.getColumnValue()));
                    }
                }
            }
        }

        totalRecords = (long) criteria.setProjection(Projections.rowCount()).uniqueResult();

        tx.commit();
    } catch (Exception e) {
        logger.error("Exception while getting getTotalRecords", e);
        if (tx != null)
            try {
                tx.rollback();
            } catch (Exception e2) {
                logger.warn("Error during rollback", e2);
            }
    } finally {
        try {
            if (session != null)
                session.close();
        } catch (Exception e2) {
            logger.warn("Error during session close", e2);
        }
    }

    return (int) totalRecords;
}

From source file:com.dell.asm.asmcore.asmmanager.db.DiscoveryResultDAO.java

License:Open Source License

/**
 * Retrieve DiscoveryResult based on parent job id.
 * @return the list of discovery results for given parent job id.
 *///from   w w w . jav  a  2 s. co  m
@SuppressWarnings("unchecked")
public List<DiscoveryResultEntity> getDiscoveryResult(String parentJobId,
        List<SortParamParser.SortInfo> sortInfos, List<FilterParamParser.FilterInfo> filterInfos,
        PaginationInfo paginationInfo) throws AsmManagerDAOException {

    Session session = null;
    Transaction tx = null;
    List<DiscoveryResultEntity> entityList = new ArrayList<DiscoveryResultEntity>();

    logger.debug("getDiscoveryResult for job: " + parentJobId);

    try {

        int offset = paginationInfo.getOffset();
        int limit = paginationInfo.getLimit();
        int pageSize = limit;

        session = _dao._database.getNewSession();
        tx = session.beginTransaction();

        Criteria criteria = session.createCriteria(DiscoveryResultEntity.class);
        BaseDAO.addSortCriteria(criteria, sortInfos);
        criteria.add(Restrictions.ne("serverType", Server.ServerType.BLADE.value())); // never return blades
        criteria.add(Restrictions.ne("serverType", Server.ServerType.COMPELLENT.value())); // never return compellents which now show up as iDrac7
        List<FilterParamParser.FilterInfo> notFound = BaseDAO.addFilterCriteria(criteria, filterInfos,
                DiscoveryResultEntity.class);

        if (notFound != null && notFound.size() > 0) {
            criteria.createAlias("discoveryResultEntity", "discoveryResultEntityAlias");
            for (FilterParamParser.FilterInfo filterInfo : notFound) {
                criteria.add(
                        Restrictions.eq("discoveryResultEntityAlias.deviceKey", filterInfo.getColumnName()));
                if (filterInfo.getColumnValue().size() == 1) {
                    criteria.add(Restrictions.eq("discoveryResultEntityAlias.deviceValue",
                            filterInfo.getColumnValue().get(0)));
                } else if (filterInfo.getColumnValue().size() > 1) {
                    criteria.add(Restrictions.in("discoveryResultEntityAlias.deviceValue",
                            filterInfo.getColumnValue()));
                }
            }
        }

        //criteria.setFirstResult((pageNumber - 1) * pageSize);
        criteria.setFirstResult(offset);
        criteria.setMaxResults(pageSize);

        entityList = criteria.list();

        // Commit transaction.
        tx.commit();
        logger.debug("getDiscoveryResult for job: " + entityList.size());
    } catch (Exception e) {
        logger.warn("Caught exception during get discovery result for job: " + parentJobId + ", " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during get device: " + ex);
        }
        //throw new AsmManagerDAOException("Caught exception during get discovery result for jobId: "    + parentJobId + ", "  + e, e);
        throw new AsmManagerInternalErrorException("Error Getting Discovery result", "DiscoveryResultDAO", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during get device: " + ex);
        }
    }

    return entityList;
}

From source file:com.dell.asm.asmcore.asmmanager.db.DiscoveryResultDAO.java

License:Open Source License

/**
 * Retrieve all from DiscoveryResultEntity.
 * @return list of entities//from  ww w.  j  a  v a 2s.  c o  m
 */
@SuppressWarnings("unchecked")
public List<DiscoveryResultEntity> getAllDiscoveryResult(List<SortParamParser.SortInfo> sortInfos,
        List<FilterParamParser.FilterInfo> filterInfos, PaginationInfo paginationInfo)
        throws AsmManagerDAOException {

    Session session = null;
    Transaction tx = null;
    List<DiscoveryResultEntity> entityList = new ArrayList<DiscoveryResultEntity>();

    try {

        int offset = paginationInfo.getOffset();
        int limit = paginationInfo.getLimit();
        int pageSize = limit;

        session = _dao._database.getNewSession();
        tx = session.beginTransaction();

        Criteria criteria = session.createCriteria(DiscoveryResultEntity.class);
        BaseDAO.addSortCriteria(criteria, sortInfos);

        List<FilterParamParser.FilterInfo> notFound = BaseDAO.addFilterCriteria(criteria, filterInfos,
                DiscoveryResultEntity.class);

        if (notFound != null && notFound.size() > 0) {
            criteria.createAlias("discoveryResultEntity", "discoveryResultEntityAlias");
            for (FilterParamParser.FilterInfo filterInfo : notFound) {
                criteria.add(Restrictions.eq("discoveryResultEntity.deviceKey", filterInfo.getColumnName()));
                if (filterInfo.getColumnValue().size() == 1) {
                    criteria.add(Restrictions.eq("discoveryResultEntityAlias.deviceValue",
                            filterInfo.getColumnValue().get(0)));
                } else if (filterInfo.getColumnValue().size() > 1) {
                    criteria.add(Restrictions.in("discoveryResultEntityAlias.deviceValue",
                            filterInfo.getColumnValue()));
                }
            }
        }

        //criteria.setFirstResult((pageNumber - 1) * pageSize);
        criteria.setFirstResult(offset);
        criteria.setMaxResults(pageSize);

        entityList = criteria.list();
        tx.commit();
    } catch (Exception e) {
        logger.warn("Caught exception during get all discovery entities: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during get all discovery entities: " + ex);
        }
        throw new AsmManagerDAOException("Caught exception during get all discover entities: ", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during get all discover entities: " + ex);
        }
    }

    return entityList;
}