List of usage examples for org.hibernate Criteria setFetchMode
public Criteria setFetchMode(String associationPath, FetchMode mode) throws HibernateException;
From source file:com.arg.arsoft.siantluis.repository.imp.ReservationRepository.java
@Override public Map findByQuery(ReservationQuery query) { int pageSize = Configs.PAGE_SIZE; Criteria criteria = factory.getCurrentSession().createCriteria(Reservation.class); if (query.getCode() != null && !query.getCode().equals("")) { if (query.getCode().contains("*") || query.getCode().contains("?")) { criteria.add(Restrictions.like("code", query.getCode().replace("*", "%").replace("?", "_"))); } else {// w w w.jav a2 s . c om criteria.add(Restrictions.eq("code", query.getCode())); } } if (query.getDescription() != null && !query.getDescription().equals("")) { if (query.getDescription().contains("*") || query.getDescription().contains("?")) { criteria.add(Restrictions.like("description", query.getDescription().replace("*", "%").replace("?", "*"))); } else { criteria.add(Restrictions.eq("description", query.getDescription())); } } if (query.getRequestBy() != null && !query.getRequestBy().equals("")) { criteria.createAlias("reservationBy", "em", JoinType.LEFT_OUTER_JOIN); criteria.add(Restrictions.eq("em.code", query.getRequestBy())); } if (query.getReservationDateFrom() != null) { criteria.add(Restrictions.ge("reservationDate", query.getReservationDateFrom())); } if (query.getReservationDateTo() != null) { criteria.add(Restrictions.le("reservationDate", query.getReservationDateTo())); } long totalRecord = (long) criteria.setProjection(Projections.count(Projections.id().toString())) .uniqueResult(); int start = ((query.getPage() - 1) * pageSize); criteria.setProjection(null); criteria.setFetchMode("reservationBy", FetchMode.JOIN); List<Reservation> result = criteria.setFirstResult(start).setMaxResults(pageSize) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); long totalPage = totalRecord / pageSize; if ((totalRecord % pageSize) > 0) { totalPage++; } List<Integer> pages = new ArrayList<Integer>(); for (int index = 1; index <= totalPage; index++) { pages.add(index); } Map data = new HashMap(); data.put("list", result); data.put("totalPage", totalPage); data.put("totalRecord", totalRecord); data.put("pages", pages); return data; }
From source file:com.arg.arsoft.siantluis.repository.imp.SupplierRepository.java
@Override public Supplier findByKey(Integer key) { Criteria criteria = factory.getCurrentSession().createCriteria(Supplier.class); criteria.setFetchMode("address", FetchMode.JOIN); criteria.setFetchMode("contact", FetchMode.JOIN); criteria.setFetchMode("address.province", FetchMode.JOIN); criteria.setFetchMode("address.amphur", FetchMode.JOIN); criteria.add(Expression.eq("id", key)); List<Supplier> result = criteria.list(); if (result != null && result.size() > 0) { return result.get(0); } else {// w w w. j a v a 2 s.c om return null; } }
From source file:com.arg.arsoft.siantluis.repository.imp.SupplierRepository.java
@Override public Map findByQuery(SupplierQuery query) { int pageSize = Configs.PAGE_SIZE; Criteria criteria = factory.getCurrentSession().createCriteria(Supplier.class); // criteria.createAlias("address.amphur","a",JoinType.LEFT_OUTER_JOIN); if (query.getCode() != null && !query.getCode().equals("")) { if (query.getCode().contains("*") || query.getCode().contains("?")) { criteria.add(Expression.like("code", query.getCode().replace("*", "%").replace("?", "_"))); } else {//from w w w.j a va2 s . c om criteria.add(Expression.eq("code", query.getCode())); } } if (query.getName() != null && !query.getName().equals("")) { if (query.getName().contains("*") || query.getName().contains("?")) { criteria.add(Expression.like("name", query.getName().replace("*", "%").replace("?", "_"))); } else { criteria.add(Expression.eq("name", query.getName())); } } if (query.getCompany() != null && !query.getCompany().equals("")) { if (query.getCompany().contains("*") || query.getCompany().contains("?")) { criteria.add(Expression.like("compny", query.getCompany().replace("*", "%").replace("?", "_"))); } else { criteria.add(Expression.eq("compny", query.getCompany())); } } if (query.getContactName() != null && !query.getContactName().equals("")) { if (query.getContactName().contains("*") || query.getContactName().contains("?")) { criteria.add(Expression.like("contact.contactName", query.getContactName().replace("*", "%").replace("?", "_"))); } else { criteria.add(Expression.eq("contact.contactName", query.getContactName())); } } if (query.getProvince() != null && query.getProvince() != 0) { criteria.createAlias("address.province", "p", JoinType.LEFT_OUTER_JOIN); criteria.add(Expression.eq("p.id", query.getProvince())); } long totalRecord = (long) criteria.setProjection(Projections.count(Projections.id().toString())) .uniqueResult(); criteria.setProjection(null); int start = ((query.getPage() - 1) * pageSize); criteria.setFetchMode("address.province", FetchMode.JOIN); criteria.setFetchMode("address.amphur", FetchMode.JOIN); List<Supplier> result = criteria.setFirstResult(start).setMaxResults(pageSize) .setResultTransformer(Criteria.ROOT_ENTITY).list(); long totalPage = totalRecord / pageSize; if ((totalRecord % pageSize) > 0) { totalPage++; } List<Integer> pages = new ArrayList<Integer>(); for (int index = 1; index <= totalPage; index++) { pages.add(index); } Map data = new HashMap(); data.put("list", result); data.put("totalPage", totalPage); data.put("totalRecord", totalRecord); data.put("pages", pages); System.out.println(pages.size()); return data; }
From source file:com.arg.arsoft.siantluis.repository.imp.UserRepository.java
@Override public User findByKey(Integer key) { Criteria criteria = factory.getCurrentSession().createCriteria(User.class); criteria.add(Restrictions.eq("id", key)); criteria.setFetchMode("roles", FetchMode.JOIN); List<User> result = criteria.list(); if (result != null && result.size() > 0) { return result.get(0); } else {/*from ww w . j a v a2 s . c om*/ return null; } }
From source file:com.cubeia.backoffice.users.dao.UserDAOImpl.java
License:Open Source License
private Criteria createFindUserCriteria(Long userId, Long operatorId, String name, Collection<UserStatus> includeStatuses, int offset, int limit, UserOrder order, boolean ascending) { Session hbSession = getHibernateSession(); Criteria c = hbSession.createCriteria(User.class); c.createAlias("information", "information", JoinType.LEFT_OUTER_JOIN); c.setFetchMode("attributes", FetchMode.SELECT); if (userId != null) { c.add(eq("id", userId)); }/* w w w .j av a 2s. co m*/ if (operatorId != null) { c.add(eq("operatorId", operatorId)); } if (name != null && !name.isEmpty()) { c.add(Restrictions.disjunction().add(like("userName", name)).add(like("information.firstName", name)) .add(like("information.lastName", name))); } if (includeStatuses != null) { c.add(Restrictions.in("status", includeStatuses)); } if (order != null) { if (ascending) { c.addOrder(Order.asc(order.getColumnName())); } else { c.addOrder(Order.desc(order.getColumnName())); } } c.setFirstResult(offset); c.setMaxResults(limit); return c; }
From source file:com.dell.asm.asmcore.asmmanager.db.TemplateDAO.java
License:Open Source License
@SuppressWarnings("unchecked") public List<TemplateEntity> getAllTemplates(List<SortParamParser.SortInfo> sortInfos, List<FilterParamParser.FilterInfo> filterInfos, PaginationInfo paginationInfo) { Session session = null;//from w ww .j av a 2s. c o m Transaction tx = null; List<TemplateEntity> entityList = new ArrayList<>(); try { int offset = paginationInfo.getOffset(); int pageSize = paginationInfo.getLimit(); session = _dao._database.getNewSession(); tx = session.beginTransaction(); Criteria criteria = session.createCriteria(TemplateEntity.class); BaseDAO.addSortCriteria(criteria, sortInfos); List<FilterParamParser.FilterInfo> notFound = BaseDAO.addFilterCriteria(criteria, filterInfos, TemplateEntity.class); if (notFound != null && notFound.size() > 0) { criteria.createAlias("templateEntity", "templateEntityAlias"); for (FilterParamParser.FilterInfo filterInfo : notFound) { criteria.add(Restrictions.eq("templateEntityAlias.deviceKey", filterInfo.getColumnName())); if (filterInfo.getColumnValue().size() == 1) { criteria.add(Restrictions.eq("templateEntityAlias.deviceValue", filterInfo.getColumnValue().get(0))); } else if (filterInfo.getColumnValue().size() > 1) { criteria.add( Restrictions.in("templateEntityAlias.deviceValue", filterInfo.getColumnValue())); } } } //criteria.setFirstResult((pageNumber - 1) * pageSize); criteria.setFirstResult(offset); criteria.setMaxResults(pageSize); criteria.setFetchMode("policyRefEntities", FetchMode.SELECT); entityList = criteria.list(); // Collection<PolicyRefEntity> dummy; // for (TemplateEntity parm : entityList) { // dummy = parm.getPolicyRefEntities(); // dummy.isEmpty(); // } // workaround for dupliacate templates //entityList.addAll(buildUniqueList(criteria.list())); // Commit transaction. tx.commit(); } catch (Exception e) { logger.warn("Caught exception during get all templates: " + e); try { if (tx != null) { tx.rollback(); } } catch (Exception ex) { logger.warn("Unable to rollback transaction during get all templates: " + ex); } throw new AsmManagerInternalErrorException("Get All templates", "TemplateDAO", e); } finally { try { if (session != null) { session.close(); } } catch (Exception ex) { logger.warn("Unable to close session during get all devices: " + ex); } } logger.warn("Template DAO get all templates size: " + entityList.size()); return entityList; }
From source file:com.grand.ids.jdbc.knowledgemodule.id.IdKnowledgeModule.java
License:Apache License
protected Graph getGraph(final Table table, ResultSet resultSet, final UserId userId) throws Exception { final List<List<Object>> ids = getObjectIds(resultSet, table); final Graph graph = new Graph(ids.size()); doInTransaction(new Action() { public void doAction(Session session) { Set<String> idSet = new HashSet<String>(); Map<String, Integer> nodesNum = new HashMap<String, Integer>(); int num = 0; for (List<Object> id : ids) { String stringId = getStringIdPresentation(id); idSet.add(stringId);//from w w w .j av a 2 s . c om nodesNum.put(stringId, num++); } Criteria criteria = session.createCriteria(RecordInfo.class); criteria.add(Restrictions.in("recordId", idSet)); criteria.add(Restrictions.eq("tableName", table.getName())); criteria.add(Restrictions.eq("userId", userId.getUserId())); criteria.setFetchMode("friendlyRecordIds", FetchMode.JOIN); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); List<RecordInfo> recordInfos = criteria.list(); Set<String> edges = new HashSet<String>(); for (RecordInfo recordInfoA : recordInfos) { Integer nodeId = nodesNum.get(recordInfoA.getRecordId()); Set<String> friendIds = recordInfoA.getFriendlyRecordIds(); for (RecordInfo recordInfoB : recordInfos) { Integer friendNodeId = nodesNum.get(recordInfoB.getRecordId()); String edge = String.format("%d-%d", friendNodeId, nodeId); if (!edges.contains(edge)) { if (friendIds.contains(recordInfoB.getRecordId())) { graph.addEdge(nodeId, friendNodeId, 1.0); } else { graph.addEdge(nodeId, friendNodeId, getLinkPredictionScore(table, userId, session, recordInfoA, recordInfoB)); } edges.add(String.format("%d-%d", nodeId, friendNodeId)); } } } } }); return graph; }
From source file:com.grand.ids.jdbc.knowledgemodule.id.IdKnowledgeModule.java
License:Apache License
private double getLinkPredictionScore(Table table, UserId userId, Session session, RecordInfo recordInfoA, RecordInfo recordInfoB) {//from ww w . jav a 2 s.c om if (linkPredictionMode == LinkPredictionMode.ADAMIC_ADAR) { Set<String> intersection = new HashSet<String>(recordInfoA.getFriendlyRecordIds()); intersection.retainAll(recordInfoB.getFriendlyRecordIds()); if (intersection.size() > 0) { Criteria criteria = session.createCriteria(RecordInfo.class); criteria.add(Restrictions.in("recordId", intersection)); criteria.add(Restrictions.eq("tableName", table.getName())); criteria.add(Restrictions.eq("userId", userId.getUserId())); criteria.setFetchMode("friendlyRecordIds", FetchMode.JOIN); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); List<RecordInfo> recordInfos = criteria.list(); double sum = 0; for (RecordInfo recordInfo : recordInfos) { sum += Math.log(2) / Math.log(recordInfo.getFriendlyRecordIds().size()); } double score = sum / intersection.size(); if ((score > 1.0) || (score < 0.0)) { throw new RuntimeException("Error!"); } return score; } else { return 0.0; } } else if (linkPredictionMode == LinkPredictionMode.JACCARD) { Set<String> friendsA = recordInfoA.getFriendlyRecordIds(); Set<String> friendsB = recordInfoB.getFriendlyRecordIds(); Set<String> union = new HashSet<String>(friendsA); union.addAll(friendsB); Set<String> intersection = new HashSet<String>(friendsA); intersection.retainAll(friendsB); System.out.println(intersection.size() + " " + union.size() + " : " + ((union.size() > 0) ? (double) intersection.size() / union.size() : 0.0)); return (union.size() > 0) ? ((double) intersection.size()) / union.size() : 0.0; } return 0.0; }
From source file:com.grand.ids.jdbc.knowledgemodule.id.IdKnowledgeModule.java
License:Apache License
private void updateRecordInfos(final String tableName, final List<List<Object>> ids, final UserId userId) { doInTransaction(new Action() { public void doAction(Session session) { Set<String> idSet = new HashSet<String>(); for (List<Object> id : ids) { idSet.add(getStringIdPresentation(id)); }/*from w w w.ja v a2s. c o m*/ Criteria criteria = session.createCriteria(RecordInfo.class); criteria.add(Restrictions.in("recordId", idSet)); criteria.add(Restrictions.eq("tableName", tableName)); criteria.add(Restrictions.eq("userId", userId.getUserId())); criteria.setFetchMode("friendlyRecordIds", FetchMode.JOIN); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); List<RecordInfo> recordInfos = criteria.list(); Set<String> nonExistIds = new HashSet<String>(idSet); for (RecordInfo recordInfo : recordInfos) { recordInfo.getFriendlyRecordIds().addAll(idSet); recordInfo.setHits(recordInfo.getHits() + 1); session.update(recordInfo); nonExistIds.remove(recordInfo.getRecordId()); } for (String id : nonExistIds) { RecordInfo recordInfo = new RecordInfo(); recordInfo.setRecordId(id); recordInfo.setTableName(tableName); recordInfo.setFriendlyRecordIds(idSet); recordInfo.setHits(1L); recordInfo.setUserId(userId.getUserId()); session.save(recordInfo); } } }); }
From source file:com.griffinslogistics.db.helpers.BookspackagesHelper.java
public List<Bookspackage> getBookspackagesByTransport(Transportation transportationForBookspackage) { logger.log(Level.SEVERE, "{0}: getBookspackagesByTransport started", CLASS_NAME); List<Bookspackage> resultList = new ArrayList<Bookspackage>(); this.session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = this.session.beginTransaction(); try {/*from w w w.j av a2s . c om*/ Criteria criteria = this.session.createCriteria(Transportation.class); criteria.add(Restrictions.eq("id", transportationForBookspackage.getId())); criteria.setFetchMode("bookspackages", FetchMode.JOIN); criteria.setFetchMode("bookspackages.truckGroup", FetchMode.JOIN); criteria.setFetchMode("bookspackages.books", FetchMode.JOIN); criteria.setFetchMode("bookspackages.books.boxes", FetchMode.JOIN); transportationForBookspackage = (Transportation) criteria.uniqueResult(); // transportationForBookspackage = (Transportation) this.session.get(Transportation.class, transportationForBookspackage.getId()); // transportationForBookspackage.getBookspackages().size(); transaction.commit(); Set<Bookspackage> bookspackages = transportationForBookspackage.getBookspackages(); for (Bookspackage bookspackage : bookspackages) { int totalBooksCount = 0; double totalBooksWeight = 0; int totalOrderedBooksCount = 0; double totalOrderedBooksWeight = 0; for (Book book : bookspackage.getBooks()) { if (book.isDiscarded()) { bookspackage.setHasDiscardedBooks(true); } totalOrderedBooksCount += book.getCount(); totalOrderedBooksWeight += book.getWeight(); for (Box box : (Set<Box>) book.getBoxes()) { int boxesCount = box.getBoxesCount(); int booksCount = box.getBooksCount(); totalBooksCount += boxesCount * booksCount; totalBooksWeight += boxesCount * booksCount * book.getWeightPerBook(); } } TruckGroup truckGroup = bookspackage.getTruckGroup(); if (truckGroup != null) { truckGroup.getName(); } totalBooksWeight = Math.round(totalBooksWeight); totalOrderedBooksWeight = Math.round(totalOrderedBooksWeight); bookspackage.setTotalBooksCount(totalBooksCount); bookspackage.setTotalBooksWeight(totalBooksWeight); bookspackage.setTotalOrderedBooksCount(totalOrderedBooksCount); bookspackage.setTotalOrderedBooksWeight(totalOrderedBooksWeight); resultList.add(bookspackage); } } catch (HibernateException e) { if (transaction.isActive()) { transaction.rollback(); } BookspackagesHelper.logger.log(Level.SEVERE, e.getMessage()); } finally { logger.log(Level.SEVERE, "{0}: getBookspackagesByTransport finished", CLASS_NAME); this.session.close(); } Collections.reverse(resultList); return resultList; }