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:es.sm2.openppm.core.dao.TeamMemberDAO.java

License:Open Source License

/**
 * Filter table utility/*  w  ww  . ja  v  a 2 s.c  o m*/
 * 
 * @param filter
 * @param joins
 * @param listResourcepool
 * @return
 * @throws ParseException
 */
public List<Teammember> filter(FiltroTabla filter, ArrayList<String> joins, List<Resourcepool> listResourcepool)
        throws ParseException {

    Criteria crit = getSession().createCriteria(getPersistentClass())
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).setFirstResult(filter.getDisplayStart())
            .setMaxResults(filter.getDisplayLength());

    // Apply filters
    applyFilters(crit, filter.getFiltro(), filter.getOrden(), listResourcepool);

    // Add data needed
    if (joins != null) {
        for (String join : joins) {
            crit.setFetchMode(join, FetchMode.JOIN);
        }
    }

    return crit.list();
}

From source file:es.sm2.openppm.core.dao.TeamMemberDAO.java

License:Open Source License

/**
 * Find team members filter by activity and status list
 *
 * @param activity/*  w ww .  j  a v a2 s .  c  om*/
 * @param statusList
 * @param joins
 * @return
 */
public List<Teammember> findByActivityAndStatus(Projectactivity activity, List<String> statusList,
        List<String> joins) {

    Criteria crit = getSession().createCriteria(getPersistentClass());

    if (joins != null) {
        for (String join : joins) {
            crit.setFetchMode(join, FetchMode.JOIN);
        }
    }

    crit.add(Restrictions.eq(Teammember.PROJECTACTIVITY, activity))
            .add(Restrictions.in(Teammember.STATUS, statusList));

    return crit.list();
}

From source file:es.sm2.openppm.core.dao.TeamMemberDAO.java

License:Open Source License

/**
 * Find team members filter by activity, employee and dates
 * /*from ww  w .j  a va 2  s .c  o  m*/
 * @param employee
 * @param projectactivity
 * @param dateIn
 * @param dateOut
 * @param joins
 * @return
 */
public List<Teammember> findByActivityAndDates(Employee employee, Projectactivity projectactivity, Date dateIn,
        Date dateOut, List<String> joins) {

    Criteria crit = getSession().createCriteria(getPersistentClass());

    if (joins != null) {
        for (String join : joins) {
            crit.setFetchMode(join, FetchMode.JOIN);
        }
    }

    crit.add(Restrictions.eq(Teammember.EMPLOYEE, employee))
            .add(Restrictions.eq(Teammember.PROJECTACTIVITY, projectactivity));

    // Filter by dates (since && until)
    if (dateIn != null && dateOut != null) {

        crit.add(Restrictions.disjunction().add(Restrictions.between(Teammember.DATEIN, dateIn, dateOut))
                .add(Restrictions.between(Teammember.DATEOUT, dateIn, dateOut))
                .add(Restrictions.and(Restrictions.le(Teammember.DATEIN, dateIn),
                        Restrictions.ge(Teammember.DATEOUT, dateOut))));
    } else if (dateIn != null) {
        crit.add(Restrictions.and(Restrictions.le(Teammember.DATEIN, dateIn),
                Restrictions.ge(Teammember.DATEOUT, dateIn)));
    } else if (dateOut != null) {
        crit.add(Restrictions.and(Restrictions.le(Teammember.DATEIN, dateOut),
                Restrictions.ge(Teammember.DATEOUT, dateOut)));
    }

    return crit.list();
}

From source file:es.sm2.openppm.core.dao.TeamMemberDAO.java

License:Open Source License

/**
 * Search team members by filters//from  ww  w. ja  v a2  s. com
 * 
 * @param list
 * @param propertyOrder
 * @param typeOrder
 * @param joins 
 * @return
 */
public List<Teammember> findByFilters(ArrayList<PropertyRelation> list, String propertyOrder, String typeOrder,
        List<String> joins) {

    Criteria crit = getSession().createCriteria(getPersistentClass());

    if (joins != null) {
        for (String join : joins) {
            crit.setFetchMode(join, FetchMode.JOIN);
        }
    }

    for (PropertyRelation propertyRelation : list) {
        crit.add(findRestriction(propertyRelation));
    }

    addOrder(crit, propertyOrder, typeOrder);

    return crit.list();
}

From source file:es.sm2.openppm.core.dao.TimesheetDAO.java

License:Open Source License

/**
 * Search timesheet by filters/*  w w  w . ja v a2s  .  c  o m*/
 * @param list
 * @param properyOrder
 * @param typeOrder
 * @param joins 
 * @return
 */
@SuppressWarnings("unchecked")
public List<Timesheet> findByFilters(ArrayList<PropertyRelation> list, String propertyOrder, String typeOrder,
        List<String> joins) {

    Criteria crit = getSession().createCriteria(getPersistentClass());

    if (joins != null) {
        for (String join : joins) {
            crit.setFetchMode(join, FetchMode.JOIN);
        }
    }

    for (PropertyRelation propertyRelation : list) {
        crit.add(findRestriction(propertyRelation));
    }

    addOrder(crit, propertyOrder, typeOrder);

    return crit.list();
}

From source file:es.sm2.openppm.core.dao.WBSNodeDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Wbsnode> searchByCode(Wbsnode node) {
    Criteria crit = getSession().createCriteria(getPersistentClass());

    crit.setFetchMode(Wbsnode.PROJECTACTIVITIES, FetchMode.JOIN);
    crit.add(Example.create(node).excludeZeroes()).add(Restrictions.eq(Wbsnode.PROJECT, node.getProject()));

    return crit.list();
}

From source file:es.sm2.openppm.utils.hibernate.dao.AbstractGenericHibernateDAO.java

License:Open Source License

protected void addJoins(Criteria crit, List<String> joins) {
    if (joins != null) {
        for (String join : joins) {
            crit.setFetchMode(join, FetchMode.JOIN);
        }/*from www . ja v a2s  .  c om*/
    }
}

From source file:eu.ist_phosphorus.harmony.idb.database.hibernate.Reservation.java

License:Open Source License

/**
 * load all reservations from DB which lie in a given time-period.
 *///from  ww  w .j  a v  a2 s.  c om
@SuppressWarnings("unchecked")
public static final Set<Reservation> loadAllInPeriod(Date startTime, Date endTime) throws DatabaseException {
    return (Set<Reservation>) (new TransactionManager(new Tuple<Date, Date>(startTime, endTime)) {
        @Override
        protected void dbOperation() {
            Set<Reservation> result = new HashSet<Reservation>();
            Tuple<Date, Date> times = (Tuple<Date, Date>) this.arg;
            // select all reservation-IDs from ReservationPeriod-view, which
            // lie in the given time-period
            DetachedCriteria ids = DetachedCriteria.forClass(VIEW_ReservationPeriod.class)
                    .setProjection(Property.forName("reservationId"))
                    .add(Restrictions.disjunction()
                            .add(Restrictions.between("startTime", times.getFirstElement(),
                                    times.getSecondElement()))
                            .add(Restrictions.between("endTime", times.getFirstElement(),
                                    times.getSecondElement()))
                            .add(Restrictions.and(Restrictions.le("startTime", times.getFirstElement()),
                                    Restrictions.ge("endTime", times.getSecondElement()))));

            // select all reservations from DB accoring to the IDs from step
            // one
            final List<Reservation> tmpReservation = this.session.createCriteria(Reservation.class)
                    .add(Subqueries.propertyIn("reservationId", ids))
                    // use join-select, because all infos will be
                    // needed later
                    .setFetchMode("Reservation", FetchMode.JOIN).list();
            for (Reservation r : tmpReservation) {
                result.add(r);
            }
            this.result = result;
        }
    }).getResult();
}

From source file:eu.jangos.manager.controller.AccountService.java

License:Apache License

/**
 * This method will login the account based on the given parameters.
 * /*from  ww  w  .  j av  a2 s  . c om*/
 * @param name The name of the account to log in.
 * @param password The password of the account trying to log in.
 * @return The logged in account.
 * @throws LoginException is thrown if there is an issue while authenticating this account.
 */
public Account login(String name, char[] password) throws LoginException {
    String hashpass = null;
    try {
        hashpass = Utils.createHashPass(name, new String(password));
    } catch (NoSuchAlgorithmException ex) {
        throw new LoginException("There was an error while generating the hashpass.");
    }

    Account account = null;
    name = name.replaceAll("[^\\dA-Za-z ]", "").replaceAll("\\s+", "+");

    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        account = (Account) session.createCriteria(Account.class).setFetchMode("locale", FetchMode.JOIN)
                .setFetchMode("realm", FetchMode.JOIN)
                .setFetchMode("bannedaccountsForFkBannedaccount", FetchMode.JOIN)
                .add(Restrictions.and(Restrictions.like("name", name), Restrictions.like("hashPass", hashpass)))
                .uniqueResult();
    } catch (HibernateException he) {
        throw new LoginException(
                "There was an error while trying to retrieve the account information from the database.");
    }

    if (account == null) {
        throw new LoginException("This account does not exist");
    }

    if (account.isLocked()) {
        throw new LoginException(
                "This account is locked, we don't think you should be allowed to manage the database.");
    }

    if (isAccountBanned(account)) {
        throw new LoginException(
                "This account is banned, we don't think you should be allowed to manage the database.");
    }

    return account;
}

From source file:eu.jangos.manager.controller.AccountService.java

License:Apache License

/**
 * Provides access to the list of all accounts matching the parameters.
 *
 * The DateFilter works the same way: - NONE does not apply any filter. -
 * BEFORE & AFTER uses only the "From" date as filter. - BETWEEN uses both
 * "From" & "To" dates as filters./*from   ww w  .  j a  v a  2 s . co m*/
 *
 * @param name The name of the accounts to be found. Can contain %.
 * @param createdFilter The filter type for the creation date.
 * @param createdFrom The first creation date filter.
 * @param createdTo The second creation date filter.
 * @param loginFilter The filter type for the login date.
 * @param loginFrom The first login date filter.
 * @param loginTo The second login date filter.
 * @param locked The filter type for the lock value.
 * @param banned The filter type for the ban value.
 * @param online The filter type for the online value.
 * @param locale The locale on which this search must filter.
 * @param realm The locale on which this search must filter.
 * @return A List of Accounts matching the criterias.
 */
public List<Account> getAllAccounts(String name, DateType createdFilter, Date createdFrom, Date createdTo,
        DateType loginFilter, Date loginFrom, Date loginTo, BooleanType locked, BooleanType banned,
        BooleanType online, Locale locale, Realm realm) {

    boolean error = false;
    String message = "You must enter the following parameters:\n";

    // Checking name input.
    if (name == null || name.isEmpty()) {
        logger.error("The parameter name is null or empty");
        message += "- A name\n";
        error = true;
    }

    // Checking dates input.
    if ((createdFilter != DateType.NONE && createdFrom == null)
            || (createdFilter == DateType.BETWEEN && createdTo == null)
            || (loginFilter != DateType.NONE && loginFrom == null)
            || (loginFilter == DateType.BETWEEN && loginTo == null)) {
        logger.error("A date filter has been requested while the date values are incorrect");
        message += "- Valid dates when selecting a date filter\n";
        error = true;
    }

    if (error) {
        throw new IllegalArgumentException(message);
    }

    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        Criteria query = session.createCriteria(Account.class, "acc");

        query.setFetchMode("locale", FetchMode.JOIN);
        query.setFetchMode("realm", FetchMode.JOIN);

        query.add(Restrictions.like("name", name));

        // This ban check is generating 2 SQL queries while, in SQL, you could do it in one.
        // Limitations of the criteria API.
        switch (banned) {
        case TRUE:
            // First, we get the list of IDs for the accounts that are banned.
            Criteria getBannedQuery = session.createCriteria(Account.class)
                    .setProjection(Projections.distinct(Projections.property("id")))
                    .createCriteria("bannedaccountsForFkBannedaccount", "ban", JoinType.LEFT_OUTER_JOIN)
                    .add(Restrictions.eq("ban.active", true));

            // Then we add these IDs to the query.
            query.add(Restrictions.in("id", getBannedQuery.list()));
            break;
        case FALSE:
            // First, we get the list of ID for the accounts that are not banned.
            Criteria getNotBanQuery = session.createCriteria(Account.class)
                    .setProjection(Projections.distinct(Projections.property("id")))
                    .createCriteria("bannedaccountsForFkBannedaccount", "ban", JoinType.LEFT_OUTER_JOIN)
                    .add(Restrictions.or(Restrictions.eq("ban.active", false),
                            Restrictions.isNull("ban.active")));

            // Then we add these IDs to the query.
            query.add(Restrictions.in("id", getNotBanQuery.list()));
            break;
        }

        // We add the realm restrictions, if it applies.
        if (!realm.getName().equals("ALL")) {
            query.add(Restrictions.eq("realm", realm));
        }

        // We add the locale restrictions, if it applies.
        if (!locale.getLocale().equals("ALL")) {
            query.add(Restrictions.eq("locale", locale));
        }

        query = Utils.applyDateFilter(query, "creation", createdFilter, createdFrom, createdTo);
        query = Utils.applyDateFilter(query, "lastlogin", loginFilter, loginFrom, loginTo);
        query = Utils.applyBooleanFilter(query, "locked", locked);
        query = Utils.applyBooleanFilter(query, "online", online);

        return query.list();
    } catch (HibernateException he) {
        logger.error("There was an error connecting to the database.");
        return null;
    }
}