io.heming.accountbook.facade.RecordQuerier.java Source code

Java tutorial

Introduction

Here is the source code for io.heming.accountbook.facade.RecordQuerier.java

Source

/*
 * Copyright 2015 heming.keh@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.heming.accountbook.facade;

import io.heming.accountbook.entity.Record;
import io.heming.accountbook.util.DateUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.*;

import java.util.Arrays;
import java.sql.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by Keh on 2015/6/3.
 */
public class RecordQuerier {
    private Date startDate;
    private Date endDate;
    private int firstIndex;
    private int maxSize;
    private String orderBy;
    private boolean desc;
    private String keyword;

    private RecordQuerier(Date startDate, Date endDate, String keyword, String orderBy, boolean desc,
            int firstIndex, int maxSize) {
        this.startDate = startDate;
        this.endDate = endDate;
        this.firstIndex = firstIndex;
        this.maxSize = maxSize;
        this.orderBy = orderBy;
        this.desc = desc;
        this.keyword = keyword;
    }

    public int count() throws Exception {
        int c = 0;
        Session session = FacadeUtil.getSessionFactory().getCurrentSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Criteria criteria = session.createCriteria(Record.class);
            buildCriteria(criteria);
            c = ((Number) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
            tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            throw e;
        }
        return c;
    }

    public double totalSales() throws Exception {
        double sales = 0;
        Session session = FacadeUtil.getSessionFactory().getCurrentSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Criteria criteria = session.createCriteria(Record.class);
            buildCriteria(criteria);
            sales = ((Number) criteria.setProjection(Projections.sum("price")).uniqueResult()).doubleValue();
            tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            throw e;
        }
        return sales;
    }

    public List<Record> query() throws Exception {
        List<Record> entities = null;
        Session session = FacadeUtil.getSessionFactory().getCurrentSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Criteria criteria = session.createCriteria(Record.class);
            buildCriteria(criteria);
            entities = criteria.list();
            tx.commit();
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            throw e;
        }
        return entities;
    }

    /**
     * ??????Criteria.
     *
     * @param criteria
     */
    private void buildCriteria(Criteria criteria) {
        // 
        if (startDate != null) {
            criteria.add(Restrictions.ge("date", startDate));
        }
        if (endDate != null) {
            criteria.add(Restrictions.le("date", endDate));
        }

        // ?
        if (keyword != null && keyword.length() > 0) {
            criteria.createAlias("category", "c");
            for (String item : keyword.split("\\s")) {
                Junction or = Restrictions.disjunction();
                // ???
                or.add(Restrictions.like("c.name", item, MatchMode.ANYWHERE));
                // ?\d\d\.\d????
                if (Pattern.matches("\\d+\\.\\d+", item)) {
                    or.add(Restrictions.eq("price", Double.parseDouble(item)));
                }
                // ???3????
                if (Pattern.matches("\\d{3,11}", item)) {
                    or.add(Restrictions.like("phone", item, MatchMode.ANYWHERE));
                }
                // ?
                or.add(Restrictions.like("note", item, MatchMode.ANYWHERE));
                criteria.add(or);
            }
        }

        // 
        criteria.setFirstResult(firstIndex).setMaxResults(maxSize);

        // ?
        if (orderBy != null) {
            Order order = desc ? Order.desc(orderBy) : Order.asc(orderBy);
            criteria.addOrder(order);
        }
    }

    public static final class Builder {
        private static final List<String> columns = Arrays.asList("id", "category", "price", "phone", "date",
                "note");

        private Date startDate;
        private Date endDate;
        private int firstIndex;
        private int maxSize;
        private String orderBy;
        private boolean desc;
        private String keyword;

        public Builder() {
            firstIndex = 0;
            maxSize = 1000;
            desc = false;
            keyword = "";
        }

        public Builder start(Date startDate) {
            this.startDate = startDate;
            return this;
        }

        public Builder year() {
            startDate = DateUtil.getStartOfYear();
            endDate = DateUtil.getNow();
            return this;
        }

        public Builder month() {
            startDate = DateUtil.getStartOfMonth();
            endDate = DateUtil.getNow();
            return this;
        }

        public Builder week() {
            startDate = DateUtil.getStartOfWeek();
            endDate = DateUtil.getNow();
            return this;
        }

        public Builder day() {
            startDate = DateUtil.getStartOfDay();
            endDate = DateUtil.getNow();
            return this;
        }

        public Builder end(Date endDate) {
            this.endDate = endDate;
            return this;
        }

        public Builder first(int firstIndex) {
            this.firstIndex = firstIndex;
            return this;
        }

        public Builder max(int maxSize) {
            this.maxSize = maxSize;
            return this;
        }

        public Builder order(String orderBy, boolean desc) {
            if (orderBy != null && !columns.contains(orderBy)) {
                throw new IllegalArgumentException(String.format("%s is not valid attribute name", orderBy));
            }
            this.orderBy = orderBy;
            this.desc = desc;
            return this;
        }

        public Builder keyword(String keyword) {
            this.keyword = keyword;
            return this;
        }

        public RecordQuerier make() {
            return new RecordQuerier(startDate, endDate, keyword, orderBy, desc, firstIndex, maxSize);
        }
    }

}