com.bookselling.dao.TradeDaoImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.bookselling.dao.TradeDaoImpl.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bookselling.dao;

import com.bookselling.domain.Address;
import com.bookselling.domain.PhoneNumber;
import com.bookselling.domain.Trade;
import com.bookselling.domain.User;
import com.bookselling.form.filter.TradeFilterForm;
import com.bookselling.form.orderby.SortType;
import com.bookselling.form.orderby.TradeOrderType;
import com.bookselling.form.searchby.TradeFilterType;
import com.bookselling.util.PaginationData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Phan Phat
 */
@Repository
public class TradeDaoImpl extends GenericDao<Trade> implements TradeDao {

    @Override
    public Class<Trade> registeredClass() {
        return Trade.class;
    }

    @Override
    public PaginationData<Trade> get(User user, int first, int items) {
        Criteria criteria = getSession().createCriteria(Trade.class);
        criteria.createAlias("buyer", "byer").add(Restrictions.eq("byer.id", user.getId()));

        criteria.setFirstResult(first);
        criteria.setMaxResults(items);

        Set<Trade> trades = new HashSet<>(criteria.list());
        HibernateInitSupport.setCls(Trade.class);
        for (Trade trade : trades)
            HibernateInitSupport.initDomain(trade);

        PaginationData paginationData = new PaginationData(
                (long) criteria.setProjection(Projections.rowCount()).uniqueResult(), items, first, trades);

        return paginationData;
    }

    @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();
    }

    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));
            }
        }

        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 };
    }

    @Override
    public PaginationData<Trade> filter(TradeFilterForm form, int first, int items) {
        Object[] data = filterCriteria(form, first, items, -1);
        Criteria criteria = (Criteria) data[0];

        Set<Trade> trades = new LinkedHashSet<>(criteria.list());
        HibernateInitSupport.setCls(Trade.class);
        for (Trade trade : trades)
            HibernateInitSupport.initDomain(trade);

        PaginationData paginationData = new PaginationData((long) data[1], items, first, trades);

        return paginationData;
    }

    @Override
    public PaginationData<Trade> filterByUser(User user, TradeFilterForm form, int first, int items) {
        Object[] data = filterCriteria(form, first, items, user.getId());
        Criteria criteria = (Criteria) data[0];

        Set<Trade> trades = new LinkedHashSet<>(criteria.list());
        HibernateInitSupport.setCls(Trade.class);
        for (Trade trade : trades)
            HibernateInitSupport.initDomain(trade);

        PaginationData paginationData = new PaginationData((long) data[1], items, first, trades);

        return paginationData;
    }
}