Example usage for org.hibernate FetchMode JOIN

List of usage examples for org.hibernate FetchMode JOIN

Introduction

In this page you can find the example usage for org.hibernate FetchMode JOIN.

Prototype

FetchMode JOIN

To view the source code for org.hibernate FetchMode JOIN.

Click Source Link

Document

Fetch using an outer join.

Usage

From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java

License:Apache License

private <T extends ObjectType> void fillTransitiveHierarchy(RObject descendant, String ancestorOid,
        Session session, boolean withIncorrect) throws SchemaException {

    Criteria cOrgClosure = session.createCriteria(ROrgClosure.class).createCriteria("descendant", "desc")
            .setFetchMode("descendant", FetchMode.JOIN).add(Restrictions.eq("oid", ancestorOid));

    List<ROrgClosure> orgClosure = cOrgClosure.list();

    if (orgClosure.size() > 0) {
        for (ROrgClosure o : orgClosure) {
            String anc = "null";
            if (o != null && o.getAncestor() != null) {
                anc = o.getAncestor().getOid();
            }/*from  w  w w  .  j a v a2  s.  c  o m*/
            LOGGER.trace("adding {}\t{}\t{}",
                    new Object[] { anc, descendant == null ? null : descendant.getOid(), o.getDepth() + 1 });

            boolean existClosure = existOrgCLosure(session, o.getAncestor().getOid(), descendant.getOid(),
                    o.getDepth() + 1);
            if (!existClosure)
                session.save(new ROrgClosure(o.getAncestor(), descendant, o.getDepth() + 1));
        }
    } else if (withIncorrect) {
        boolean existIncorrect = existIncorrect(session, ancestorOid, descendant.getOid());
        if (!existIncorrect) {
            LOGGER.trace("adding incorrect {}\t{}", new Object[] { ancestorOid, descendant.getOid() });
            session.save(new ROrgIncorrect(ancestorOid, descendant.getOid()));
        }
    }
}

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);/* w  ww  .  ja  va 2s  . c  o m*/
                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   www. ja v a2  s . com
    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));
            }/* ww  w . j  av a 2s  . c  om*/
            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.book.BookDAO.java

@Override
public List<Book> getAllById(List<Long> selectedBookIds) {
    return this.sessionFactory.getCurrentSession().createCriteria(Book.class)
            .setFetchMode(Bookspackage.class.getName(), FetchMode.JOIN)
            .add(Restrictions.in("id", selectedBookIds)).list();
}

From source file:com.griffinslogistics.book.BookService.java

@Override
public List<BookLabelModel> getLabelInfoForBooks(List<Long> selectedBookIds) {

    DetachedCriteria criteria = DetachedCriteria.forClass(Book.class)
            .setFetchMode(Bookspackage.class.getName(), FetchMode.JOIN)
            .add(Restrictions.in("id", selectedBookIds));

    List<Book> books = (List<Book>) this.dao.getAllByDetachedCriteria(criteria);

    List<BookLabelModel> result = new ArrayList<BookLabelModel>();

    if (books != null && !books.isEmpty()) {
        Transport transport = (Transport) books.get(0).getTransport();

        for (Book book : books) {
            BookLabelModel model = new BookLabelModel(book.getDeliveryAddress(),
                    book.getBookspackage().getPostalCode(), book.getTitle(), book.getBookNumber(),
                    book.getBookspackage().getClient(), transport.getWeekNumber() + "/" + transport.getYear(),
                    (long) book.getCount(), book.getBookspackage().getPackageNumber(), book.getISBN());

            result.add(model);/*from  w  ww. ja v  a  2 s .com*/
        }
    }

    return result;
}

From source file:com.griffinslogistics.book.BookService.java

@Override
public List<BookForTransportationModel> getBooksForTransportModelByTransportId(Long transportId) {
    logger.log(Level.SEVERE, "{0}: getBooksForTransportation started", CLASS_NAME);

    List<BookForTransportationModel> resultList = new ArrayList<BookForTransportationModel>();

    try {//w  ww  . j  a  v  a 2 s .  com

        DetachedCriteria criteria = DetachedCriteria.forClass(Transport.class);
        criteria.add(Restrictions.eq("id", transportId));
        criteria.setFetchMode("books", FetchMode.JOIN);
        criteria.setFetchMode("books.boxes", FetchMode.JOIN);

        Transport transportation = (Transport) this.dao.getByDetachedCriteria(criteria);

        for (Book book : transportation.getBooks()) {
            Hibernate.initialize(book.getBoxes());

            if (book.getPrintingHouse() != null) {
                book.getPrintingHouse().getName();
            }

            BookForTransportationModel model = BookForTransportationModel.fromBook(book);
            resultList.add(model);
        }

        Collections.reverse(resultList);
    } catch (HibernateException e) {
        logger.log(Level.SEVERE, e.getMessage());
    } finally {

        logger.log(Level.SEVERE, "{0}: getBooksForTransportation finished", CLASS_NAME);
    }

    return resultList;
}

From source file:com.griffinslogistics.bookspackage.BookspackageService.java

@Override
public List<Bookspackage> getBookspackagesByTransportId(Long transportId) {

    DetachedCriteria criteria = DetachedCriteria.forClass(Transport.class);
    criteria.add(Restrictions.eq("id", transportId));
    criteria.setFetchMode("bookspackages", FetchMode.JOIN);
    criteria.setFetchMode("bookspackages.truckGroup", FetchMode.JOIN);
    criteria.setFetchMode("bookspackages.books", FetchMode.JOIN);
    criteria.setFetchMode("bookspackages.boxes", FetchMode.JOIN);
    criteria.setFetchMode("bookspackages.books.boxes", FetchMode.JOIN);

    Transport transportationForBookspackage = (Transport) this.dao.getByDetachedCriteria(criteria);

    List<Bookspackage> bookspackages = new ArrayList(transportationForBookspackage.getBookspackages());

    for (Bookspackage bookspackage : bookspackages) {

        BookspackagePriorityEnum priorityEnum = BookspackagePriorityEnum.byValue(bookspackage.getPriority());
        bookspackage.setDisplayPriority(priorityEnum.getDisplayValue());

        int totalBooksCount = 0;
        double totalBooksWeight = 0;
        int totalOrderedBooksCount = 0;
        double totalOrderedBooksWeight = 0;
        int totalBoxesCount = 0;

        for (Book book : bookspackage.getBooks()) {

            if (book.isDiscarded()) {
                bookspackage.setHasDiscardedBooks(true);
            }/*from ww  w.j a  v  a 2  s .  co m*/

            totalOrderedBooksCount += book.getCount();
            totalOrderedBooksWeight += book.getWeight();

            for (Box box : book.getBoxes()) {
                int boxesCount = box.getBoxesCount();
                int booksCount = box.getBooksCount();

                totalBooksCount += boxesCount * booksCount;
                totalBooksWeight += boxesCount * booksCount * book.getWeightPerBook();
                totalBoxesCount += boxesCount;
            }
        }

        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);
        bookspackage.setBoxesCount(totalBoxesCount);
    }

    Collections.reverse(bookspackages);
    return bookspackages;
}

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 {//  ww w .  j a va2  s.  com
        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;
}

From source file:com.griffinslogistics.db.helpers.DeliveriesHelper.java

@Override
public List<Delivery> getAllDeliveries() {
    logger.log(Level.SEVERE, "{0}: getAllDeliveries started", CLASS_NAME);

    this.session = HibernateUtil.getSessionFactory().openSession();
    List<Delivery> result = new ArrayList<Delivery>();
    Transaction transaction = this.session.beginTransaction();

    try {/*from  www  .  j  av  a  2s. c om*/
        Criteria criteria = this.session.createCriteria(Delivery.class);
        result = (List<Delivery>) criteria
                //                    .setFetchMode("attachments", FetchMode.JOIN)
                .setFetchMode("deliverydirection", FetchMode.JOIN).list();

        transaction.commit();
    } catch (HibernateException e) {
        transaction.rollback();
        DeliveriesHelper.logger.log(Level.SEVERE, e.getMessage());
    } finally {
        this.session.close();
        logger.log(Level.SEVERE, "{0}: getAllDeliveries finished", CLASS_NAME);

    }

    Collections.reverse(result);
    return result;
}