Example usage for org.hibernate Session saveOrUpdate

List of usage examples for org.hibernate Session saveOrUpdate

Introduction

In this page you can find the example usage for org.hibernate Session saveOrUpdate.

Prototype

void saveOrUpdate(Object object);

Source Link

Document

Either #save(Object) or #update(Object) the given instance, depending upon resolution of the unsaved-value checks (see the manual for discussion of unsaved-value checking).

Usage

From source file:com.duroty.application.mail.manager.PreferencesManager.java

License:Open Source License

/**
 * DOCUMENT ME!//w ww.j  ava2 s  .co  m
 *
 * @param hsession DOCUMENT ME!
 * @param token DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws ManagerException DOCUMENT ME!
 */
public void createFilter(Session hsession, String repositoryName, FilterObj filter) throws MailException {
    String lucenePathMessages = null;

    if (!defaultLucenePath.endsWith(File.separator)) {
        lucenePathMessages = defaultLucenePath + File.separator + repositoryName + File.separator
                + Constants.MAIL_LUCENE_MESSAGES;
    } else {
        lucenePathMessages = defaultLucenePath + repositoryName + File.separator
                + Constants.MAIL_LUCENE_MESSAGES;
    }

    Searcher searcher = null;

    try {
        searcher = MailIndexer.getSearcher(lucenePathMessages);

        Users user = getUser(hsession, repositoryName);

        if (user != null) {
            Criteria critLabel = hsession.createCriteria(Label.class);
            critLabel.add(Restrictions.eq("users", user));
            critLabel.add(Restrictions.eq("labIdint", new Integer(filter.getLabel().getIdint())));

            Label hlabel = (Label) critLabel.uniqueResult();

            if (hlabel == null) {
                hlabel = new Label();
                hlabel.setUsers(user);
                hlabel.setLabName(filter.getLabel().getName());
                hsession.save(hlabel);
                hsession.flush();
            }

            Filter hfilter = new Filter();

            //hfilter.setUser(user);
            hfilter.setLabel(hlabel);
            hfilter.setFilArchive(filter.isArchive());
            hfilter.setFilDoesntHaveWords(filter.getDoesntHaveWords());
            hfilter.setFilForwardTo(filter.getForward());
            hfilter.setFilFrom(filter.getFrom());

            //CANVIDUROT
            hfilter.setFilHasAttacment(filter.isHasAttachment());
            hfilter.setFilHasWords(filter.getHasWords());
            hfilter.setFilImportant(filter.isImportant());
            hfilter.setFilSubject(filter.getSubject());
            hfilter.setFilTo(filter.getTo());
            hfilter.setFilTrash(filter.isTrash());
            hfilter.setFilOrOperator(!filter.isOperator());

            hsession.save(hfilter);
            hsession.flush();

            org.apache.lucene.search.Query query = FilterQueryParser.parse(hfilter, analyzer);

            if ((searcher != null) && (query != null)) {
                Hits hits = searcher.search(query);

                for (int j = 0; j < hits.length(); j++) {
                    Document doc = hits.doc(j);
                    String uid = doc.get(Field_idint);

                    Criteria crit = hsession.createCriteria(Message.class);
                    crit.add(Restrictions.eq("mesName", uid));
                    crit.add(Restrictions.eq("users", user));

                    Message message = (Message) crit.uniqueResult();

                    if (message != null) {
                        try {
                            LabMesId id = new LabMesId();
                            id.setLabel(hlabel);
                            id.setMessage(message);

                            LabMes lm = new LabMes(id);
                            hsession.saveOrUpdate(lm);
                            hsession.flush();
                        } catch (HibernateException e) {
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        throw new MailException(ex);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.mail.manager.PreferencesManager.java

License:Open Source License

/**
 * DOCUMENT ME!//from www . jav  a 2  s.  co m
 *
 * @param hsession DOCUMENT ME!
 * @param token DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws ManagerException DOCUMENT ME!
 */
public void updateFilter(Session hsession, String repositoryName, FilterObj filter) throws MailException {
    String lucenePathMessages = null;

    if (!defaultLucenePath.endsWith(File.separator)) {
        lucenePathMessages = defaultLucenePath + File.separator + repositoryName + File.separator
                + Constants.MAIL_LUCENE_MESSAGES;
    } else {
        lucenePathMessages = defaultLucenePath + repositoryName + File.separator
                + Constants.MAIL_LUCENE_MESSAGES;
    }

    Searcher searcher = null;

    try {
        searcher = MailIndexer.getSearcher(lucenePathMessages);

        Users user = getUser(hsession, repositoryName);

        if (user != null) {
            Criteria crit1 = hsession.createCriteria(Label.class);
            crit1.add(Restrictions.eq("labIdint", filter.getLabel().getIdint()));
            crit1.add(Restrictions.eq("users", user));

            Label hlabel = (Label) crit1.uniqueResult();

            Filter hfilter = (Filter) hsession.load(Filter.class, filter.getIdint());

            hfilter.setFilArchive(filter.isArchive());
            hfilter.setFilDoesntHaveWords(filter.getDoesntHaveWords());
            hfilter.setFilForwardTo(filter.getForward());
            hfilter.setFilFrom(filter.getFrom());

            //CANVIDUROT
            hfilter.setFilHasAttacment(filter.isHasAttachment());
            hfilter.setFilHasWords(filter.getHasWords());
            hfilter.setFilImportant(filter.isImportant());
            hfilter.setFilSubject(filter.getSubject());
            hfilter.setFilTo(filter.getTo());
            hfilter.setFilTrash(filter.isTrash());
            hfilter.setFilOrOperator(!filter.isOperator());

            hfilter.setLabel(hlabel);

            hsession.update(hfilter);
            hsession.flush();

            org.apache.lucene.search.Query query = FilterQueryParser.parse(hfilter, analyzer);

            if ((searcher != null) && (query != null)) {
                Hits hits = searcher.search(query);

                for (int j = 0; j < hits.length(); j++) {
                    Document doc = hits.doc(j);
                    String uid = doc.get(Field_idint);

                    Criteria crit2 = hsession.createCriteria(Message.class);
                    crit2.add(Restrictions.eq("mesName", uid));
                    crit2.add(Restrictions.eq("users", user));

                    Message message = (Message) crit2.uniqueResult();

                    if (message != null) {
                        try {
                            LabMesId id = new LabMesId();
                            id.setLabel(hlabel);
                            id.setMessage(message);

                            LabMes lm = new LabMes(id);
                            hsession.saveOrUpdate(lm);
                            hsession.flush();
                        } catch (HibernateException e) {
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        throw new MailException(ex);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.mail.manager.PreferencesManager.java

License:Open Source License

/**
 * DOCUMENT ME!//from  w  ww. j av  a  2 s.  c o  m
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param contactObj DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void addContact(Session hsession, String repositoryName, String action, ContactObj contactObj)
        throws MailException {
    Contact contact = null;

    try {
        Users user = getUser(hsession, repositoryName);

        //if ((action != null) && action.equals("update")) {
        Criteria crit = hsession.createCriteria(Contact.class);
        crit.add(Restrictions.eq("users", user));
        crit.add(Restrictions.eq("conEmail", contactObj.getEmail()));

        contact = (Contact) crit.uniqueResult();
        //}

        if (contact == null) {
            contact = new Contact();
        }

        contact.setConDescription(contactObj.getDescription());
        contact.setConEmail(contactObj.getEmail());
        contact.setConName(contactObj.getName());
        contact.setConReceivedDate(new Date());
        contact.setConSentDate(new Date());
        contact.setConCount(contact.getConCount() + 1);
        contact.setUsers(user);

        hsession.saveOrUpdate(contact);

        hsession.flush();
    } catch (Exception e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.duroty.application.mail.manager.PreferencesManager.java

License:Open Source License

/**
 * DOCUMENT ME!/*from   ww  w  . j  a  v  a2s .co  m*/
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param name DOCUMENT ME!
 * @param emails DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void addGroup(Session hsession, String repositoryName, String action, String name, String emails)
        throws MailException {
    ContactList contactList = null;

    try {
        Users user = getUser(hsession, repositoryName);

        InternetAddress[] tos = MessageUtilities.encodeAddresses(emails, null);

        if ((action != null) && action.equals("update")) {
            Criteria crit = hsession.createCriteria(ContactList.class);
            crit.add(Restrictions.eq("users", user));
            crit.add(Restrictions.eq("coliName", name));

            contactList = (ContactList) crit.uniqueResult();
        }

        if (contactList == null) {
            contactList = new ContactList();

            contactList.setColiName(name);
            contactList.setUsers(user);

            for (int i = 0; i < tos.length; i++) {
                Criteria crit = hsession.createCriteria(Contact.class);
                crit.add(Restrictions.eq("users", user));
                crit.add(Restrictions.eq("conEmail", tos[i].getAddress()));

                Contact contact = (Contact) crit.uniqueResult();

                if (contact == null) {
                    contact = new Contact();
                    contact.setConEmail(tos[i].getAddress());
                    contact.setConName(tos[i].getPersonal());
                    contact.setUsers(user);

                    hsession.saveOrUpdate(contact);
                    hsession.flush();
                }

                ConColiId id = new ConColiId(contact, contactList);
                contactList.addConColi(new ConColi(id));
            }

            hsession.saveOrUpdate(contactList);
            hsession.flush();
        } else {
            contactList.setColiName(name);
            contactList.setUsers(user);

            for (int i = 0; i < tos.length; i++) {
                Criteria crit = hsession.createCriteria(Contact.class);
                crit.add(Restrictions.eq("users", user));
                crit.add(Restrictions.eq("conEmail", tos[i].getAddress()));

                Contact contact = (Contact) crit.uniqueResult();

                if (contact == null) {
                    contact = new Contact();
                    contact.setConEmail(tos[i].getAddress());
                    contact.setConName(tos[i].getPersonal());
                    contact.setUsers(user);

                    hsession.saveOrUpdate(contact);
                    hsession.flush();
                }

                ConColiId id = new ConColiId(contact, contactList);
                contactList.addConColi(new ConColi(id));
            }

            hsession.saveOrUpdate(contactList);
            hsession.flush();
        }
    } catch (Exception e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.dz.module.charge.ChargeService.java

/**
 * ???,/*from   www  . j a  v a 2  s .  c  om*/
 * @param dept 
 * @return true if success
 */
public boolean finalClearAll(String dept) {
    //?????
    if (!("".equals(dept) || "".equals(dept) || "".equals(dept)))
        return false;
    Date totalTime = clearTimeDao.getCurrent("total");
    Date deptTime = clearTimeDao.getCurrent(dept);
    if (!DateUtil.isYearAndMonth(totalTime, deptTime))
        return false;
    List<Contract> contractList = contractDao.contractSearchAllAvilable(deptTime, dept, null, null);
    //TODOI don't know if it is necessary to filter
    fileterContract(contractList);
    //        for(Contract contract:contractList){
    //            Driver d = new Driver();
    //            d.setIdNum(contract.getIdNum());
    //            Driver driver = driverDao.selectById(d.getIdNum());
    //            //TODO wait to add department
    //            if(driver != null && dept.equals(contract.getBranchFirm())){
    //                clear(contract.getId(),deptTime);
    //            }
    //           clear(contract.getId(),deptTime);
    //        }

    List<CheckChargeTable> tables = this.getAllCheckChargeTable(deptTime, dept, null, 4);

    Session session = HibernateSessionFactory.getSession();
    Transaction tx = null;

    try {
        tx = session.beginTransaction();

        for (Contract contract : contractList) {
            clear(contract.getId(), deptTime);
        }

        String hql = "select c1,c2 from Contract c1,Contract c2 where c1.contractFrom=c2.id and (c2.abandonedFinalTime is null or (YEAR(c2.abandonedFinalTime)*12+MONTH(c2.abandonedFinalTime)+(case when DAY(c2.abandonedFinalTime)>26 then 1 else 0 end) >= (YEAR(:currentClearTime)*12+MONTH(:currentClearTime)) ))";

        Query query = session.createQuery(hql);
        query.setDate("currentClearTime", deptTime);

        List<Object[]> list = query.list();

        for (Object[] oarr : list) {
            Contract c = (Contract) oarr[0];
            Contract oc = (Contract) oarr[1];

            if (c.getAccount() == null)
                c.setAccount(BigDecimal.ZERO);

            if (oc.getAccount() != null)
                c.setAccount(c.getAccount().add(oc.getAccount()));

            oc.setAccount(BigDecimal.ZERO);
            session.saveOrUpdate(c);
            session.saveOrUpdate(oc);
        }

        //??
        boolean res = clearTimeDao.plusAMonth(dept, session);
        Date time1 = clearTimeDao.getCurrent("", session);
        Date time2 = clearTimeDao.getCurrent("", session);
        Date time3 = clearTimeDao.getCurrent("", session);
        if (!DateUtil.isYearAndMonth(totalTime, time1) && !DateUtil.isYearAndMonth(totalTime, time2)
                && !DateUtil.isYearAndMonth(totalTime, time3)) {
            clearTimeDao.plusAMonth("total", session);
        } else {
            System.out.println(dept);
            System.out.println(res);
            System.out.println(time1);
            System.out.println(time2);
            System.out.println(time3);
            System.out.println(totalTime);
        }

        for (CheckChargeTable cct : tables) {
            session.save(cct);
        }

        tx.commit();
    } catch (HibernateException ex) {
        ex.printStackTrace();
        if (tx != null)
            tx.rollback();
        return false;
    } finally {
        HibernateSessionFactory.closeSession();
    }

    return true;
}

From source file:com.dz.module.charge.ChargeService.java

/**
 * ??//from  ww  w  . ja  v a 2 s. com
 * @param contractId none
 * @param clearTime none
 * @return none
 */
private boolean clear(int contractId, Date clearTime) throws HibernateException {
    Session session = HibernateSessionFactory.getSession();
    Contract c = (Contract) session.get(Contract.class, contractId);
    BigDecimal account = c.getAccount();
    //?
    ChargePlan lastMonthRecord = new ChargePlan();
    lastMonthRecord.setFee(account);
    lastMonthRecord.setIsClear(true);
    lastMonthRecord.setContractId(contractId);
    lastMonthRecord.setTime(clearTime);
    lastMonthRecord.setFeeType("last_month_left");
    session.saveOrUpdate(lastMonthRecord);

    Query query = session.createQuery(
            "from ChargePlan where contractId = :contractId and isClear=false and year(time)=year(:date) and month(time)=month(:date)");
    query.setInteger("contractId", contractId);
    query.setDate("date", clearTime);

    //        List<ChargePlan> plans = chargeDao.getUnclears(contractId,clearTime);
    List<ChargePlan> plans = query.list();

    for (ChargePlan plan : plans) {
        //            System.out.println(plan.getFeeType() + " test "+plan.getFee());
        String feeType = plan.getFeeType();
        if (feeType.startsWith("add") || feeType.startsWith("plan_sub")) {
            account = account.add(plan.getFee());
        } else if (feeType.startsWith("sub") || feeType.startsWith("plan_add")
                || feeType.startsWith("plan_base")) {
            account = account.subtract(plan.getFee());
        }
        //            chargeDao.cleared(plan);
        plan.setIsClear(true);
        session.saveOrUpdate(plan);
    }
    //        contractDao.updateAccount(contractId,account);
    c.setAccount(account);
    session.saveOrUpdate(c);

    return true;
}

From source file:com.dz.module.charge.ChargeService.java

/**
 * ???,???//from  w w  w  . ja v a  2  s . c o  m
 * @param plan
 * @return
 */
public void addChargePlan(ChargePlan plan, Session session) throws HibernateException {
    if (plan == null)
        throw new HibernateException("the plan shouldn't be null");
    plan.setIsClear(false);
    int contractId = plan.getContractId();
    Contract contract = (Contract) session.get(Contract.class, contractId);
    if (contract == null)
        return;
    //??????.
    if (!plan.getFeeType().equals("plan_base_contract"))
        if ((plan.getFeeType().startsWith("add") || plan.getFeeType().startsWith("sub"))) {
            if (!DateUtil.isYearAndMonth(plan.getTime(),
                    clearTimeDao.getCurrent(contract.getBranchFirm(), session)))
                return;
        } else {
            plan.setTime(clearTimeDao.getCurrent(contract.getBranchFirm(), session));
        }
    if (plan.getFee() == null)
        return;
    session.saveOrUpdate(plan);
}

From source file:com.dz.module.contract.ContractDaoImpl.java

public boolean contractWrite(Contract contract) throws HibernateException {
    boolean flag = false;
    Session session = null;
    Transaction tx = null;/*  w  w w  .j  av a2s  .c  om*/
    try {
        session = HibernateSessionFactory.getSession();
        tx = (Transaction) session.beginTransaction();

        session.saveOrUpdate(contract);
        tx.commit();
        flag = true;
    } catch (HibernateException e) {
        if (tx != null) {
            tx.rollback();
        }
        throw e;
    } finally {
        HibernateSessionFactory.closeSession();
    }
    return flag;
}

From source file:com.dz.module.contract.ContractDaoImpl.java

@Override
public boolean addRentFirstDivide(RentFirstDivide rentFirstDivide) {
    Session session = null;
    Transaction tx = null;/*from w  w  w  .j a  v  a 2  s.c om*/
    try {
        session = HibernateSessionFactory.getSession();
        tx = (Transaction) session.beginTransaction();

        session.saveOrUpdate(rentFirstDivide);
        tx.commit();
        return true;
    } catch (HibernateException e) {
        if (tx != null) {
            tx.rollback();
        }
        return false;
    } finally {
        HibernateSessionFactory.closeSession();
    }
}

From source file:com.dz.module.vehicle.InsuranceDaoImpl.java

@Override
public void addInsurance(Insurance insurance) throws HibernateException {
    Session session = null;
    Transaction tx = null;//from ww  w  . j a  va  2  s  .c  om
    try {
        session = HibernateSessionFactory.getSession();
        tx = (Transaction) session.beginTransaction();
        insurance.setInsuranceNum(StringUtils.upperCase(insurance.getInsuranceNum()));
        session.saveOrUpdate(insurance);
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null) {
            tx.rollback();
        }
        throw e;
    } finally {
        HibernateSessionFactory.closeSession();
    }
}