CountryGroupRepositoryImpl.java

package com.tradecloud.repository.impl;

import com.tradecloud.domain.configuration.CountryGroup;
import com.tradecloud.domain.costing.CostDefinition;
import com.tradecloud.domain.costing.CostableCostDefinition;
import com.tradecloud.domain.place.Country;
import com.tradecloud.dto.costing.costsetup.CountryGroupSearch;
import com.tradecloud.repository.CountryGroupRepository;
import com.tradecloud.repository.base.impl.RepositoryBaseImpl;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * Created by ds on 2015/07/22.
 */
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public class CountryGroupRepositoryImpl extends RepositoryBaseImpl<CountryGroup, CountryGroupSearch> implements CountryGroupRepository {

    @Override
    public List<CountryGroup> search(CountryGroupSearch countryGroupSearch) {
        Criteria searchCriteria = getSessionCustom().createCriteria(CountryGroup.class);
        if (countryGroupSearch.getCode() != null)
            searchCriteria.add(Restrictions.ilike("code", "%" + countryGroupSearch.getCode() + "%"));
        if (countryGroupSearch.getName() != null)
            searchCriteria.add(Restrictions.ilike("name", "%" + countryGroupSearch.getName() + "%"));
        @SuppressWarnings("unchecked") List<CountryGroup> results = searchCriteria.list();
        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<CountryGroup> findByCountry(Country countryOfOrigin) {
        String countryGrpHql = "Select cg from CountryGroups cg inner join cg.countries c where c.code=:countrycode";
        Query query = getSession().createQuery(countryGrpHql);
        query.setParameter("countrycode", countryOfOrigin.getCode());
        return query.list();
    }

    public boolean inUse(CountryGroup countryGroup) {
        Criteria criteria = getSessionCustom().createCriteria(CostDefinition.class);
        criteria.add(Restrictions.eq("countryGroup", countryGroup));
        criteria.setProjection(Projections.rowCount());
        Long count = (Long) criteria.uniqueResult();
        if (!Objects.isNull(count) && count.intValue() > 0) {
            return true;
        }

        criteria = getSessionCustom().createCriteria(CostableCostDefinition.class);
        criteria.add(Restrictions.eq("countryGroup", countryGroup));
        criteria.setProjection(Projections.rowCount());
        count = (Long) criteria.uniqueResult();
        if (!Objects.isNull(count) && count.intValue() > 0) {
            return true;
        }

        return false;
    }
}