List of usage examples for org.hibernate Criteria createAlias
public Criteria createAlias(String associationPath, String alias) throws HibernateException;
From source file:com.bookselling.dao.TradeDaoImpl.java
@Override public Trade get(User user, int id) { Criteria criteria = getSession().createCriteria(Trade.class); criteria.createAlias("buyer", "byer").add(Restrictions.eq("byer.id", user.getId())) .add(Restrictions.eq("id", id)); Set<Trade> trades = new HashSet<>(criteria.list()); HibernateInitSupport.setCls(Trade.class); for (Trade trade : trades) HibernateInitSupport.initDomain(trade); return trades.iterator().next(); }
From source file:com.bookselling.dao.TradeDaoImpl.java
private Object[] filterCriteria(TradeFilterForm form, int first, int items, int id) { String keyword = form.getKeyword(); TradeFilterType searchBy = form.getSearchBy(); Date fromDate = form.getFromDate(); Date toDate = form.getToDate(); Double fromPrice = form.getFromPrice(); Double toPrice = form.getToPrice(); TradeOrderType orderBy = form.getOrderBy(); SortType sortType = form.getSortType(); Criteria criteria = getSession().createCriteria(Trade.class); criteria.createAlias("buyer", "bye").createAlias("bye.account", "acc"); if (keyword != null) { keyword = "%" + keyword + "%"; if (searchBy == TradeFilterType.ADDRESS) { Address address = new Address(); address.setAddress(keyword); criteria.add(Restrictions.like("contact.address", address)); } else if (searchBy == TradeFilterType.PHONE) { PhoneNumber phone = new PhoneNumber(); phone.setPhoneNumber(keyword); criteria.add(Restrictions.like("contact.phoneNumber", phone)); }//from www .j a v a 2s. c o m } if (fromDate != null) criteria.add(Restrictions.ge("createdDate", fromDate)); if (toDate != null) criteria.add(Restrictions.le("createdDate", toDate)); if (fromPrice != null) criteria.add(Restrictions.ge("totalPrice", fromPrice)); if (toPrice != null) criteria.add(Restrictions.le("totalPrice", toPrice)); String propertyName = null; if (orderBy == TradeOrderType.BUYER) propertyName = "acc.username"; else if (orderBy == TradeOrderType.OWNER) propertyName = "bye.name"; else if (orderBy == TradeOrderType.DATE) propertyName = "createdDate"; else if (orderBy == TradeOrderType.PRICE) propertyName = "totalPrice"; if (id != -1) criteria.add(Restrictions.eq("bye.id", id)); //Ly s dng long rowCount = (long) criteria.setProjection(Projections.countDistinct("id")).uniqueResult(); //Ly id criteria.setProjection(null).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) .setProjection(Projections.distinct(Projections.id())).setFirstResult(first).setMaxResults(items) .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName)); List<Integer> ids = new ArrayList<>(); for (Iterator<Integer> temp = criteria.list().iterator(); temp.hasNext();) ids.add(temp.next()); //Criteria ph Criteria subCriteria = getSession().createCriteria(Trade.class); subCriteria.createAlias("buyer", "bye").createAlias("bye.account", "acc") .add(Restrictions.in("id", ids.size() > 0 ? ids : Arrays.asList(-1))) .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName)); return new Object[] { subCriteria, rowCount }; }
From source file:com.bookselling.dao.UserDaoImpl.java
@Override public PaginationData get(int first, int items) { Criteria criteria = getSession().createCriteria(User.class); criteria.createAlias("account", "acc").createAlias("acc.role", "rl").add(Restrictions.eq("rl.id", USER_ID)); Set<User> users = new HashSet<>(criteria.list()); HibernateInitSupport.setCls(User.class); for (User user : users) HibernateInitSupport.initDomain(user); //Pagination//from w w w .j a v a 2 s .c o m PaginationData paginationData = new PaginationData( (long) criteria.setProjection(Projections.rowCount()).uniqueResult(), items, first, users); return paginationData; }
From source file:com.bookselling.dao.UserDaoImpl.java
@Override public PaginationData filter(UserFilterForm form, int first, int items) { Criteria criteria = getSession().createCriteria(User.class); //Get form data String keyword = form.getKeyword(); AccountStatus[] accStatus = form.getAccStatus(); UserFilterType searchBy = form.getSearchBy(); Date fromDate = form.getFromDate(); Date toDate = form.getToDate(); UserOrderType orderBy = form.getOrderBy(); SortType sortType = form.getSortType(); //To criteria criteria.createAlias("account", "acc").createAlias("acc.role", "rls").add(Restrictions.eq("rls.id", 1)); if (keyword != null && !keyword.isEmpty()) { keyword = "%" + keyword + "%"; if (searchBy == UserFilterType.ADDRESS) { Address address = new Address(); address.setAddress(keyword); criteria.add(Restrictions.like("contact.address", address)); } else if (searchBy == UserFilterType.EMAIL) { criteria.add(Restrictions.like("acc.email", keyword)); } else if (searchBy == UserFilterType.OWNER) { Name name = new Name(); name.setName(keyword);/*w w w . jav a 2 s . c o m*/ criteria.add(Restrictions.like("name", name)); } else if (searchBy == UserFilterType.PHONE) { PhoneNumber phone = new PhoneNumber(); phone.setPhoneNumber(keyword); criteria.add(Restrictions.like("contact.phone", phone)); } else if (searchBy == UserFilterType.USERNAME) { criteria.add(Restrictions.like("acc.username", keyword)); } } if (accStatus.length != 0) { criteria.add(Restrictions.in("acc.status", accStatus)); } if (fromDate != null) criteria.add(Restrictions.ge("acc.createdDate", fromDate)); if (toDate != null) criteria.add(Restrictions.le("acc.createdDate", toDate)); String propertyName = null; if (orderBy == UserOrderType.CREATEDDATE) propertyName = "acc.createdDate"; else if (orderBy == UserOrderType.NAME) propertyName = "name"; else if (orderBy == UserOrderType.STATUS) propertyName = "acc.status"; else if (orderBy == UserOrderType.USERNAME) propertyName = "acc.username"; //Ly s dng long rowCount = (long) criteria.setProjection(Projections.countDistinct("id")).uniqueResult(); //Ly id criteria.setProjection(null).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) .setProjection(Projections.distinct(Projections.id())).setFirstResult(first).setMaxResults(items) .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName)); List<Integer> ids = new ArrayList<>(); for (Iterator<Integer> temp = criteria.list().iterator(); temp.hasNext();) ids.add(temp.next()); //Criteria ph Criteria subCriteria = getSession().createCriteria(User.class); subCriteria.createAlias("account", "acc").createAlias("acc.role", "rls").add(Restrictions.eq("rls.id", 1)) .add(Restrictions.in("id", ids.size() > 0 ? ids : Arrays.asList(-1))) .addOrder(sortType == SortType.ASC ? Order.asc(propertyName) : Order.desc(propertyName)); //get list Set<User> users = new LinkedHashSet<>(subCriteria.list()); for (User user : users) { HibernateInitSupport.initUser(user); } //Pagination PaginationData paginationData = new PaginationData(rowCount, items, first, users); return paginationData; }
From source file:com.certus.actions.getAllProductsJsonAction.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Session s = com.certus.connection.HibernateUtil.getSessionFactory().openSession(); Criteria cr = s.createCriteria(ProductHasSize.class, "phs"); cr.createAlias("phs.product", "product").createAlias("phs.size", "size") .createAlias("product.brand", "brand").add(Restrictions.eq("product.availability", true)) .add(Restrictions.eq("brand.availability", true)) .setProjection(Projections.groupProperty("product")); List<Product> pros = cr.list(); List<ProductHasSize> newPros = new ArrayList<>(); for (Product pro : pros) { ProductHasSize ph = productDetails(pro, s); newPros.add(ph);/*from ww w.ja v a 2s. c o m*/ } GsonBuilder builder = new GsonBuilder(); Gson gson = builder.registerTypeAdapter(ProductHasSize.class, new ProductFilterTypeAdapter()).create(); String element = gson.toJson(newPros); s.close(); response.getWriter().write(element); }
From source file:com.certus.actions.mainSearchBarAction.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {// w ww . java 2 s . co m Session s = com.certus.connection.HibernateUtil.getSessionFactory().openSession(); String pNameMatch = request.getParameter("pName"); // System.out.println("Start"); Criteria cr = s.createCriteria(ProductHasSize.class, "phs"); cr.createAlias("phs.product", "product").createAlias("phs.size", "size") .createAlias("product.brand", "brand").add(Restrictions.eq("product.availability", true)) .add(Restrictions.eq("brand.availability", true)) .add(Restrictions.like("product.name", pNameMatch, MatchMode.ANYWHERE)) .setProjection(Projections.groupProperty("product")); // System.out.println("End"); List<Product> pros = cr.list(); String html = ""; html += "<div class=\"items\">\n" + " <div class=\"container\">\n" + " <div class=\"row\">\n" + " <div class=\"col-md-12\">\n" + " <h3 class=\"title\">Search Results</h3>\n" + " </div>"; Context env1 = (Context) new InitialContext().lookup("java:comp/env"); String productsPath1 = (String) env1.lookup("uploadpathproducts"); for (Product pro : pros) { ProductHasSize ph = productDetails(pro, s); html += "<div class='col-md-3 col-sm-4'>" + " <div class=\"item\">\n" + " <!-- Item image -->\n" + " \n"; if (ph.getProduct().getDiscountPrice() != 0) { html += "<span class=\"ico pull-right\"><img src=\"img/sale.png\" alt=\"\"></span>\n"; } html += " <div class=\"item-image\">\n" + " \n" + " <a href=\"single-item.jsp?cat=" + ph.getProduct().getSubCategory().getCategory().getId() + "&sub=" + ph.getProduct().getSubCategory().getId() + "&pid=" + ph.getProduct().getId() + "\"><img src=\"" + productsPath1 + ph.getProduct().getImageMain() + "\" alt=\"\" class=\"img-responsive\"></a>\n" + " </div>\n" + " <!-- Item details -->\n" + " <div class=\"item-details\">\n" + " <!-- Name -->\n" + " <!-- Use the span tag with the class \"ico\" and icon link (hot, sale, deal, new) -->\n" + " <div id=\"quickfit\">\n" + " <h5 style=\"white-space: nowrap;overflow: hidden;\"><a href=\"single-item.jsp?cat=" + ph.getProduct().getSubCategory().getCategory().getId() + "&sub=" + ph.getProduct().getSubCategory().getId() + "&pid=" + ph.getProduct().getId() + "\">" + ph.getProduct().getName() + "</a></h5>\n" + " </div>\n" + " <div class=\"clearfix\"></div>\n" + " <!-- Para. Note more than 2 lines. -->\n" + " <p>" + ph.getProduct().getBrand().getBrandName() + "</p>\n" + " <hr>\n" + " <!-- Price -->\n" + " <div class=\"item-price pull-left\">\n"; if (ph.getProduct().getDiscountPrice() != 0.0) { html += " <del>Rs. " + ph.getPrice() + "</del>\n" + " <p style=\"color: #F25758;\">Rs. " + ph.getDiscountPrice(ph.getPrice(), ph.getProduct().getDiscountPrice()) + "</p>\n"; } else { html += "Rs " + ph.getPrice(); } html += "</div>\n" + " <form action=\"addToCartAction\" method=\"GET\">\n" + " <input name=\"pro_id\" value=\"" + ph.getProduct().getId() + "\" type=\"hidden\">\n" + " <input name=\"size\" value=\"" + ph.getSize(ph.getProduct().getProductHasSizes(), ph.getProduct().getId()) + "\" type=\"hidden\">\n" + " <input name=\"qnty\" value=\"1\" type=\"hidden\">\n" + " <input name=\"dom\" value=\"tyt\" type=\"hidden\">\n" + " <div class=\"button pull-right\">\n" + " <button class=\"btn\" style=\"background-color: #F25758; color: #efd8d8;\" type=\"submit\">Add to Cart</button>\n" + " </div>\n" + " </form>\n" + " <div class=\"clearfix\"></div>\n" + " </div>\n" + "</div>\n" + "</div>"; } html += "</div></div>"; s.close(); response.getWriter().write(html); } catch (NamingException ex) { Logger.getLogger(mainSearchBarAction.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.certus.test.Test3.java
public static void main(String[] args) { // Session s = com.certus.connection.HibernateUtil.getSessionFactory().openSession(); // List<Product> proList = s.createCriteria(Product.class).list(); // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.registerTypeAdapter(Product.class, new CustomTypeAdapter()).create(); // String element = gson.toJson(proList); // System.out.println(element); // A a = new A(); // a.setAge("23"); // a.setName("aaa"); // a.setSchool("bbb college"); // try { // Map<String, String> map = BeanUtils.describe(a); ///* w ww .ja va2 s . c o m*/ // for (Map.Entry<String, String> entry : map.entrySet()) { // System.out.println(entry.getKey() + "/" + entry.getValue()); // } // // Field[] allFields = a.getClass().getFields(); // for (Field field : allFields) { // System.out.println(field.getName()); // } // // } catch (Exception e) { // } String pNameMatch = "top"; Session s = com.certus.connection.HibernateUtil.getSessionFactory().openSession(); Criteria cr = s.createCriteria(ProductHasSize.class, "phs"); cr.createAlias("phs.product", "product").createAlias("phs.size", "size") .createAlias("product.brand", "brand").add(Restrictions.eq("product.availability", true)) .add(Restrictions.eq("brand.availability", true)) .add(Restrictions.like("product.name", pNameMatch, MatchMode.ANYWHERE)) .setProjection(Projections.groupProperty("product")); List<Product> phs = cr.list(); for (Product ph : phs) { ProductHasSize pp = new Test3().productDetails(ph, s); String sl = pp.getPrice() + " - " + pp.getProduct().getName(); System.out.println(sl); } //System.out.println(phs.toArray()); // Map stateMap = new HashMap(); // for (Object[] obj : phs) { // DownloadState downloadState = (DownloadState) obj[0]; // stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]); // } }
From source file:com.court.controller.CollectionSheetFxmlController.java
private List<Member> memberList() { Session session = HibernateUtil.getSessionFactory().openSession(); Criteria c = session.createCriteria(Member.class); c.createAlias("branch", "b"); c.createAlias("payOffice", "po"); //=====================================REMOVED DUE TO UNNASSARY FILTER================================= // c.createAlias("memberLoans", "ml"); // c.add(Restrictions.eq("ml.isComplete", false)); // c.add(Restrictions.disjunction() // .add(Restrictions.le("ml.paidUntil", new java.util.Date())) // .add(Restrictions.isNull("ml.paidUntil")) // );//from ww w . j ava 2 s . com //=====================================REMOVED DUE TO UNNASSARY FILTER================================== int selected = search_typ_combo.getSelectionModel().getSelectedIndex(); switch (selected) { case 0: c.add(Restrictions.disjunction() //===================SEARCH CHANGED TO PAYMENT OFFICE INSTEAD OF USER BRANCH=================== // .add(Restrictions.eq("b.branchName", search_txt.getText()))); .add(Restrictions.eq("po.branchCode", search_txt.getText().split("-")[0]))); break; case 1: c.add(Restrictions.disjunction().add(Restrictions.eq("memberId", search_txt.getText()))); break; case 2: c.add(Restrictions.disjunction().add(Restrictions.eq("nameWithIns", search_txt.getText()))); break; } c.add(Restrictions.eq("status", true)); c.add(Restrictions.eq("b.status", true)); c.addOrder(Order.asc("b.branchCode")); List<Member> mList = c.list(); List<Member> filteredList = mList.stream().filter(FxUtilsHandler.distinctByKey(p -> p.getMemberId())) .collect(Collectors.toList()); session.close(); return filteredList; }
From source file:com.court.controller.LoginFxmlController.java
private UserHasUserRole getUserHasUsrRoleFromUser(Session session, User loggedU) { Criteria c = session.createCriteria(UserHasUserRole.class); UserHasUserRole uniqueResult = (UserHasUserRole) c.createAlias("user", "u") .add(Restrictions.eq("u.id", loggedU.getId())).uniqueResult(); return uniqueResult; }
From source file:com.court.controller.MemberfxmlController.java
private void getMemberLoanByCode(String mlCode, int childId) { Session session = HibernateUtil.getSessionFactory().openSession(); try {//w w w.ja v a 2s . c o m Criteria c = session.createCriteria(MemberLoan.class); c.add(Restrictions.eq("memberLoanCode", mlCode)); c.add(Restrictions.eq("childId", childId)); c.setMaxResults(1); MemberLoan ml = (MemberLoan) c.uniqueResult(); if (ml != null) { double prins_plus_ins = ml.getLoanInstallment() * ml.getNoOfRepay(); gurantors_lstview.getItems().clear(); loan_id_txt.setText(ml.getMemberLoanCode()); g_date_txt.setText(new SimpleDateFormat("yyyy-MM-dd").format(ml.getGrantedDate())); r_date_txt.setText( ml.getlRequested() != null ? new SimpleDateFormat("yyyy-MM-dd").format(ml.getlRequested()) : ""); l_type_txt.setText(ml.getInterestMethod()); l_amount_txt.setText(TextFormatHandler.CURRENCY_DECIMAL_FORMAT.format(ml.getLoanAmount())); l_int_txt.setText(TextFormatHandler.PRECENTAGE_DECIMAL_FORMAT.format(ml.getLoanInterest() / 100) + " " + ml.getInterestPer()); l_du_txt.setText(ml.getLoanDuration() + " " + ml.getDurationPer()); int_pls_prin_txt.setText(TextFormatHandler.CURRENCY_DECIMAL_FORMAT.format(prins_plus_ins)); bal_cont_txt.setText(TextFormatHandler.CURRENCY_DECIMAL_FORMAT.format(ml.getKotaLeft())); loan_nm_txt.setText(ml.getLoanName()); List<Member> signedGuarantors = getSignedGuarantors(ml.getGuarantors(), session); if (signedGuarantors != null) { gurantors_lstview.getItems().addAll(signedGuarantors); } double ins_only = prins_plus_ins - ml.getLoanAmount(); l_repay_txt.setText(TextFormatHandler.CURRENCY_DECIMAL_FORMAT.format(ml.getLoanInstallment()) + "( " + TextFormatHandler.CURRENCY_DECIMAL_FORMAT.format((ml.getLoanInstallment() - FxUtilsHandler.roundNumber((ins_only / ml.getLoanDuration()), 0))) + " + " + TextFormatHandler.CURRENCY_DECIMAL_FORMAT .format(FxUtilsHandler.roundNumber((ins_only / ml.getLoanDuration()), 0)) + " )"); Criteria cl = session.createCriteria(LoanPayment.class); cl.createAlias("memberLoan", "ml"); // cl.add(Restrictions.eq("ml.memberLoanCode", ml.getMemberLoanCode())); cl.add(Restrictions.eq("ml.id", ml.getId())); List<LoanPayment> filteredList = cl.list(); if (!filteredList.isEmpty()) { List<LoanPayment> collect = filteredList.stream() .filter(FxUtilsHandler.distinctByKey(p -> p.getInstallmentNo())) .collect(Collectors.toList()); double tot_pay_lo = (ml.getLoanInstallment() * ml.getNoOfRepay()); Double paymentDue = tot_pay_lo - collect.stream().mapToDouble(LoanPayment::getPaidAmt).sum(); // System.out.println("ESTIMATE - " + paymentDue); double loanComplete = ml.isClosedLoan() ? 1.0 : (paymentDue / tot_pay_lo) * 100; ReadOnlyDoubleWrapper workDone = new ReadOnlyDoubleWrapper(); ProgressIndicatorBar bar = new ProgressIndicatorBar(workDone, loanComplete); bar.createProgressIndicatorBar(progress_box, workDone); initLoanPayTable(FXCollections.observableArrayList(collect)); } else { initLoanPayTable(FXCollections.observableArrayList()); ReadOnlyDoubleWrapper workDone = new ReadOnlyDoubleWrapper(); ProgressIndicatorBar bar = new ProgressIndicatorBar(workDone, 0); bar.createProgressIndicatorBar(progress_box, workDone); } } } finally { if (session != null) { session.close(); } } }