Example usage for org.hibernate Session clear

List of usage examples for org.hibernate Session clear

Introduction

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

Prototype

void clear();

Source Link

Document

Completely clear the session.

Usage

From source file:com.autentia.intra.dao.hibernate.HibernateManagerBase.java

License:Open Source License

public ITransferObject merge(ITransferObject obj) throws DataAccException {
    Serializable pk = obj.getId();
    if (pk == null)
        return obj;

    try {/*from   www . j  ava 2  s  .c  om*/
        Session session = null;
        session = HibernateUtil.currentSession();
        session.beginTransaction();
        log.debug("objeto con clave '" + pk + "' recuperado para mezcla");
        obj = (ITransferObject) session.merge(obj);
        try {
            session.getTransaction().commit();

            log.debug("objeto con clave '" + pk + "' correctamente mezclado");
        } catch (HibernateException ex) {
            session.getTransaction().rollback();
            session.clear();
        }
    } catch (Exception ex) {
        String msg = "Error mezclando el objeto '" + obj + "' con clave primaria '" + pk + "'";
        log.debug("error mezclando el objeto '" + pk + "': " + msg);
        throw new DataAccException(msg, ex);
    }
    return obj;
}

From source file:com.baculsoft.demo.service.RegistrationService.java

public List[] getAllList() {
    logger.info("#Enter getAllList()");
    Session session = sessionFactoryPrimary.openSession();
    List listCreditCardCustomer = session.createCriteria(CreditCardCustomer.class).list();
    session.close();// w ww .j ava  2 s.com

    Session session2 = sessionFactorySecondary.openSession();
    List listCustomer = session2.createCriteria(Customer.class).list();
    session2.clear();
    logger.info("#End getAllList()");
    return new List[] { listCreditCardCustomer, listCustomer };

}

From source file:com.baomidou.hibernateplus.dao.impl.DaoImpl.java

License:Open Source License

@Override
public boolean insertBatch(List<P> list, int size) {
    Assert.notEmpty(list);//  www .ja  v  a 2 s  .  c om
    try {
        Session session = HibernateUtils.getSession(masterSession(), isCurrent());
        for (int i = 0; i < list.size(); i++) {
            session.save(list.get(i));
            if (i % size == 0) {
                session.flush();
                session.clear();
            }
        }
    } catch (Exception e) {
        logger.warn("Warn: Unexpected exception.  Cause:" + e);
        return false;
    }
    return true;
}

From source file:com.baomidou.hibernateplus.dao.impl.DaoImpl.java

License:Open Source License

@Override
public boolean updateBatch(List<P> list, int size) {
    Assert.notEmpty(list);/* ww w  . j  a v  a  2  s  .co m*/
    try {
        Session session = HibernateUtils.getSession(masterSession(), isCurrent());
        for (int i = 0; i < list.size(); i++) {
            session.merge(list.get(i));
            if (i % size == 0) {
                session.flush();
                session.clear();
            }
        }
    } catch (Exception e) {
        logger.warn("Warn: Unexpected exception.  Cause:" + e);
        return false;
    }
    return true;

}

From source file:com.baomidou.hibernateplus.dao.impl.DaoImpl.java

License:Open Source License

@Override
public boolean saveOrUpdateBatch(List<P> list, int size) {
    Assert.notEmpty(list);//  w  w w. ja v a 2s .c  o  m
    try {
        Session session = HibernateUtils.getSession(masterSession(), isCurrent());
        for (int i = 0; i < list.size(); i++) {
            session.saveOrUpdate(list.get(i));
            if (i % size == 0) {
                session.flush();
                session.clear();
            }
        }
    } catch (Exception e) {
        logger.warn("Warn: Unexpected exception.  Cause:" + e);
        return false;
    }
    return true;

}

From source file:com.britesnow.snow.web.db.hibernate.HibernateDaoHelperImpl.java

License:Apache License

public void flushAndClear() {
    Session session = getSession();
    try {//from   w  ww. j a v a 2  s .com
        session.flush();
        session.clear();
    } catch (Throwable e) {
        throw new SnowHibernateException(e);
    }
}

From source file:com.candy.db.StockEodProc.java

/**
 * insert the records into database/*  w  ww  .  j a va 2s. c  o  m*/
 * @param stockEodLst
 * @return 
 */
public boolean writeHisStockData(Collection<Stockeod> stockEodLst) {
    try {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        int count = 0;

        for (Stockeod stockEod : stockEodLst) {
            session.save(stockEod);
            if (++count % 20 == 0) {
                session.flush();
                session.clear();
            }
        }
        tx.commit();
        session.close();
        return true;
    } catch (HibernateException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.cosylab.cdb.jdal.hibernate.plugin.HibernateWDALAlarmPluginImpl.java

License:Open Source License

public static void importAlarms(Session session, Configuration config, ConfigurationAccessor conf,
        Logger m_logger) throws Exception {
    // clean up whatever is in the session
    session.getTransaction().commit();/*from w ww . j a v  a  2  s.  c o m*/
    session.clear();
    session.beginTransaction();

    // create DAOs
    ACSAlarmDAOImpl alarmDAO = new ACSAlarmDAOImpl(m_logger);
    ACSCategoryDAOImpl categoryDAO = new ACSCategoryDAOImpl(m_logger, alarmDAO);
    ACSResponsiblePersonDAOImpl responsiblePersonDAO = new ACSResponsiblePersonDAOImpl();

    // configure
    alarmDAO.setConfAccessor(conf);
    alarmDAO.setSurveillanceAlarmId("SURVEILLANCE:SOURCE:1");
    alarmDAO.setResponsiblePersonDAO(responsiblePersonDAO);

    categoryDAO.setConfAccessor(conf);
    //categoryDAO.setCategoryTreeRoot("ACS");
    categoryDAO.setCategoryTreeRoot("ROOT");
    categoryDAO.setSurveillanceCategoryPath("ACS.SURVEILLANCE");

    responsiblePersonDAO.setAlarmDAO(alarmDAO);

    // load
    final List<alma.acs.alarmsystem.generated.FaultFamily> families = alarmDAO.loadAlarms();
    final alma.acs.alarmsystem.generated.Category[] categories = categoryDAO.loadCategories();
    Map<String, ArrayList<AlarmCategory>> categoryFaultFamilyLinks = new HashMap<String, ArrayList<AlarmCategory>>();

    // store categories
    if (categories != null)
        for (alma.acs.alarmsystem.generated.Category daoCategory : categories) {
            AlarmCategory category = (AlarmCategory) session.createCriteria(AlarmCategory.class)
                    .add(Restrictions.eq("configuration", config))
                    .add(Restrictions.eq("alarmCategoryName", daoCategory.getPath())).uniqueResult();
            if (category == null) {
                category = new AlarmCategory();
                category.setAlarmCategoryName(daoCategory.getPath());
                category.setConfiguration(config);
            }
            category.setDescription(nonEmptyString(daoCategory.getDescription(), "(description)"));
            category.setPath(daoCategory.getPath());
            category.setIsDefault(daoCategory.getIsDefault());
            session.saveOrUpdate(category);

            // clear first (in case of update)
            category.getFaultFamilies().clear();

            // cache mappings
            String[] faultFamilies = daoCategory.getAlarms().getFaultFamily();
            for (String faultFamily : faultFamilies) {
                ArrayList<AlarmCategory> list = categoryFaultFamilyLinks.get(faultFamily);
                if (list == null) {
                    list = new ArrayList<AlarmCategory>();
                    categoryFaultFamilyLinks.put(faultFamily, list);
                }
                list.add(category);
            }
        }

    // store fault families and contacts, etc.
    if (families != null)
        for (alma.acs.alarmsystem.generated.FaultFamily family : families) {
            final alma.acs.alarmsystem.generated.Contact daoContact = family.getContact();
            Contact contact = (Contact) session.createCriteria(Contact.class)
                    .add(Restrictions.eq("contactName", daoContact.getName())).uniqueResult();
            if (contact == null) {
                contact = new Contact();
                contact.setContactName(nonEmptyString(daoContact.getName(), "(empty)"));
                contact.setEmail(daoContact.getEmail());
                contact.setGsm(daoContact.getGsm());
                session.persist(contact);
            }
            // If contact exist, let's check if this contact contains different information. If so,
            // issue an error
            else {
                if (!trimAndNullToEmpty(contact.getEmail()).equals(trimAndNullToEmpty(daoContact.getEmail()))
                        || !trimAndNullToEmpty(contact.getGsm())
                                .equals(trimAndNullToEmpty(daoContact.getGsm()))) {
                    throw new RuntimeException(
                            "Data stored for contact '" + contact.getContactName() + "' in TMCDB "
                                    + "does not match that comming from the 'contact' node of fault family '"
                                    + family.getName() + "'. " + "TMCDB: <" + contact.getEmail() + ", "
                                    + contact.getGsm() + ">, " + "CDB: <" + daoContact.getEmail() + ", "
                                    + daoContact.getGsm() + ">");
                }
            }

            FaultFamily faultFamily = (FaultFamily) session.createCriteria(FaultFamily.class)
                    .add(Restrictions.eq("configuration", config))
                    .add(Restrictions.eq("familyName", family.getName())).uniqueResult();
            if (faultFamily == null) {
                faultFamily = new FaultFamily();
                faultFamily.setFamilyName(family.getName());
                faultFamily.setConfiguration(config);
            }
            faultFamily.setAlarmSource(family.getAlarmSource());
            faultFamily.setHelpURL(family.getHelpUrl());
            faultFamily.setContact(contact);
            session.saveOrUpdate(faultFamily);

            // clear first (in case of update)   
            faultFamily.getAlarmCategories().clear();
            ArrayList<AlarmCategory> list = categoryFaultFamilyLinks.get(family.getName());
            if (list != null)
                for (AlarmCategory category : list) {
                    category.getFaultFamilies().add(faultFamily);
                    faultFamily.getAlarmCategories().add(category);
                    session.update(category);
                    session.update(faultFamily);
                }

            // default fault member
            if (family.getFaultMemberDefault() != null) {
                DefaultMember defaultMember = null;
                // there can be only one
                if (faultFamily.getDefaultMembers().size() != 0)
                    defaultMember = faultFamily.getDefaultMembers().iterator().next();
                if (defaultMember == null) {
                    defaultMember = new DefaultMember();
                    defaultMember.setFaultFamily(faultFamily);
                }
                defaultMember.setLocation(getLocation(session, family.getFaultMemberDefault().getLocation()));
                session.saveOrUpdate(defaultMember);
            } else {
                for (DefaultMember memberToRemove : faultFamily.getDefaultMembers()) {
                    faultFamily.getDefaultMembers().remove(memberToRemove);
                    session.delete(memberToRemove);
                }
                session.update(faultFamily);
            }

            // copy all
            Set<FaultMember> faultMembersToRemove = new HashSet<FaultMember>(faultFamily.getFaultMembers());

            // add fault members
            for (alma.acs.alarmsystem.generated.FaultMember daoFaultMember : family.getFaultMember()) {
                FaultMember faultMember = (FaultMember) session.createCriteria(FaultMember.class)
                        .add(Restrictions.eq("memberName", daoFaultMember.getName()))
                        .add(Restrictions.eq("faultFamily", faultFamily)).uniqueResult();
                faultMembersToRemove.remove(faultMember);
                if (faultMember == null) {
                    faultMember = new FaultMember();
                    faultMember.setMemberName(daoFaultMember.getName());
                    faultMember.setFaultFamily(faultFamily);
                }
                faultMember.setLocation(getLocation(session, daoFaultMember.getLocation()));
                session.saveOrUpdate(faultMember);
            }

            if (faultMembersToRemove.size() > 0) {
                for (FaultMember faultMemberToRemove : faultMembersToRemove) {
                    faultFamily.getFaultMembers().remove(faultMemberToRemove);
                    session.delete(faultMemberToRemove);
                }
                session.update(faultFamily);
            }

            // copy all
            Set<FaultCode> faultCodesToRemove = new HashSet<FaultCode>(faultFamily.getFaultCodes());

            // add fault codes
            for (alma.acs.alarmsystem.generated.FaultCode daoFaultCode : family.getFaultCode()) {
                FaultCode faultCode = (FaultCode) session.createCriteria(FaultCode.class)
                        .add(Restrictions.eq("faultFamily", faultFamily))
                        .add(Restrictions.eq("codeValue", daoFaultCode.getValue())).uniqueResult();
                faultCodesToRemove.remove(faultCode);
                if (faultCode == null) {
                    faultCode = new FaultCode();
                    faultCode.setFaultFamily(faultFamily);
                    faultCode.setCodeValue(daoFaultCode.getValue());
                }
                faultCode.setPriority(daoFaultCode.getPriority());
                faultCode.setCause(daoFaultCode.getCause());
                faultCode.setAction(daoFaultCode.getAction());
                faultCode.setConsequence(daoFaultCode.getConsequence());
                faultCode.setProblemDescription(
                        nonEmptyString(daoFaultCode.getProblemDescription(), "(description)"));
                faultCode.setIsInstant(daoFaultCode.getInstant());
                session.saveOrUpdate(faultCode);
            }

            if (faultCodesToRemove.size() > 0) {
                for (FaultCode faultCodeToRemove : faultCodesToRemove) {
                    faultFamily.getFaultCodes().remove(faultCodeToRemove);
                    session.delete(faultCodeToRemove);
                }
                session.update(faultFamily);
            }
        }

    try {
        alma.alarmsystem.alarmmessage.generated.ReductionDefinitions redDefs = alarmDAO
                .getReductionDefinitions();
        if (redDefs != null) {
            if (redDefs.getLinksToCreate() != null)
                saveReductionLinks(session, config, redDefs.getLinksToCreate().getReductionLink(),
                        ReductionLinkAction.CREATE);
            if (redDefs.getLinksToRemove() != null)
                saveReductionLinks(session, config, redDefs.getLinksToRemove().getReductionLink(),
                        ReductionLinkAction.REMOVE);

            int count = 0;
            if (redDefs.getThresholds() != null) {
                alma.alarmsystem.alarmmessage.generated.Threshold[] thresholds = redDefs.getThresholds()
                        .getThreshold();
                for (alma.alarmsystem.alarmmessage.generated.Threshold threshold : thresholds) {
                    // also commit first
                    if (count % 100 == 0) {
                        session.getTransaction().commit();
                        session.clear(); // cleanup first level cache
                        session.beginTransaction();
                        config = (Configuration) session.get(Configuration.class, config.getConfigurationId());
                    }

                    count++;

                    alma.acs.tmcdb.AlarmDefinition alarm = getAlarmDefinition(session, config,
                            threshold.getAlarmDefinition(), false);
                    alma.acs.tmcdb.ReductionThreshold t = (alma.acs.tmcdb.ReductionThreshold) session
                            .createQuery("from ReductionThreshold " + "where AlarmDefinitionId = "
                                    + alarm.getAlarmDefinitionId())
                            .uniqueResult();

                    if (t == null) {
                        t = new ReductionThreshold();
                        t.setAlarmDefinition(alarm);
                        t.setConfiguration(config);
                    }
                    t.setValue(threshold.getValue());
                    session.saveOrUpdate(t);
                }
            }
        }
    } finally {
        // clear cache (to free memory)
        adCache.clear();
    }
}

From source file:com.cosylab.cdb.jdal.hibernate.plugin.HibernateWDALAlarmPluginImpl.java

License:Open Source License

private static void saveReductionLinks(Session session, Configuration config,
        alma.alarmsystem.alarmmessage.generated.ReductionLinkType[] links, ReductionLinkAction action) {
    int count = 0;

    for (alma.alarmsystem.alarmmessage.generated.ReductionLinkType link : links) {
        // also commit first
        if (count % 100 == 0) {
            session.getTransaction().commit();
            session.clear(); // cleanup first level cache
            adCache.clear();//  ww w.ja  v a 2s  .  c o  m
            session.beginTransaction();
            // refresh
            config = (Configuration) session.get(Configuration.class, config.getConfigurationId());
        }

        count++;

        alma.acs.tmcdb.AlarmDefinition parent = getAlarmDefinition(session, config,
                link.getParent().getAlarmDefinition(), true);
        alma.acs.tmcdb.AlarmDefinition child = getAlarmDefinition(session, config,
                link.getChild().getAlarmDefinition(), true);

        alma.acs.tmcdb.ReductionLink remoteLink = (alma.acs.tmcdb.ReductionLink) session
                .createCriteria(alma.acs.tmcdb.ReductionLink.class)
                .add(Restrictions.eq("alarmDefinitionByParentalarmdefid", parent))
                .add(Restrictions.eq("alarmDefinitionByChildalarmdefid", child)).uniqueResult();
        if (remoteLink == null) {

            remoteLink = new alma.acs.tmcdb.ReductionLink();
            remoteLink.setAlarmDefinitionByChildalarmdefid(child);
            remoteLink.setAlarmDefinitionByParentalarmdefid(parent);
            remoteLink.setConfiguration(config);

        }
        remoteLink.setAction(action);
        remoteLink.setType(ReductionLinkType.valueOf(link.getType().toString()));
        session.saveOrUpdate(remoteLink);
    }

    // and commit
    session.getTransaction().commit();
    session.clear();
    session.beginTransaction();
}

From source file:com.creative.dao.repository.GenericBatchDaoImpl.java

License:Apache License

private <T> int executeBatch(BatchType batchType, List<T> list) {
    Session session = sessionFactory.getCurrentSession();
    session.setCacheMode(CacheMode.IGNORE);
    session.setFlushMode(FlushMode.MANUAL);
    logger.info("Executing  Batch of size :" + list.size() + " given batch size is:" + batchSize);

    for (int i = 0; i < list.size(); i++) {
        switch (batchType) {
        case BATCH_INSERT:
            session.save(list.get(i));//from  w  ww .  j  av  a2s. com
            break;
        case BATCH_DELETE:
            session.delete(list.get(i));
            break;
        case BATCH_INSERT_OR_UPDATE:
            session.saveOrUpdate(list.get(i));
        default:
            // nothing;
        }
        if (i > 0 && i % batchSize == 0) {
            logger.info("Flushing and clearing the cache" + " after row number :" + i);
            session.flush();
            session.clear();
        }

    }
    session.flush();
    return list.size();
}