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.turborep.turbotracker.banking.service.BankingServiceImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*w  ww . ja v  a  2 s .  c o  m*/
public boolean voidTransactionDetails1(Motransaction theMotransaction, Session aSession)
        throws BankingException {
    Motransaction aMotransaction = null;
    List<Integer> veBillId = null;
    Vebill aVeBill = null;
    VeBillPaymentHistory veBillHistory = null;
    List<Molinkagedetail> theMolinkagedetail = null;
    List<Motransaction> themotranlist = null;
    String checkNo = "";

    boolean returnStatus = false;
    try {
        aMotransaction = (Motransaction) aSession.get(Motransaction.class,
                theMotransaction.getMoTransactionId());
        aMotransaction.setDescription(theMotransaction.getDescription() + "[VOID]");
        aMotransaction.setVoid_(theMotransaction.getVoid_());
        aMotransaction.setMoAccountId(theMotransaction.getMoAccountId());
        aMotransaction.setStatus(theMotransaction.getStatus());
        checkNo = theMotransaction.getReference();
        aSession.update(aMotransaction);
        /**
         * Created by: Leo Date: Apr 22,2015.
         * ID: 294 
         * Description: update veBill and veBillPaymentHistory
         * */

        //veBillId =(List<Integer>) aSession.createSQLQuery("SELECT veBillID FROM moLinkageDetail WHERE moTransactionID ="+theMotransaction.getMoTransactionId()).list();

        themotranlist = (List<Motransaction>) aSession
                .createSQLQuery("SELECT moTransactionID FROM moTransaction WHERE uniquechkRef =" + checkNo)
                .list();

        Iterator<?> amotIterator = themotranlist.iterator();
        while (amotIterator.hasNext()) {
            Integer amotObj = (Integer) amotIterator.next();
            // update all related transaction as void
            aSession.createSQLQuery("update moTransaction set Void = 1 where moTransactionID = " + amotObj)
                    .executeUpdate();

            theMolinkagedetail = (List<Molinkagedetail>) aSession.createSQLQuery(
                    "Select veBillID,Amount,Discount from moLinkageDetail where moTransactionID = " + amotObj)
                    .list();
            if (theMolinkagedetail.size() > 0) {
                Iterator<?> aIterator = theMolinkagedetail.iterator();
                while (aIterator.hasNext()) {
                    Object[] aObj = (Object[]) aIterator.next();
                    aVeBill = (Vebill) aSession.get(Vebill.class, (Integer) aObj[0]);
                    aVeBill.setAppliedAmount(aVeBill.getAppliedAmount()
                            .subtract(((BigDecimal) aObj[1]).add((BigDecimal) aObj[2])));
                    aVeBill.setTransactionStatus(1);
                    aSession.update(aVeBill);
                    aSession.createSQLQuery(
                            "Delete FROM `veBillPaymentHistory` WHERE veBillID =" + (Integer) aObj[0])
                            .executeUpdate();
                    returnStatus = true;
                }
            } else {
                returnStatus = false;
            }
        }
    } catch (Exception e) {
        itsLogger.error(e.getMessage(), e);
        BankingException aBankingException = new BankingException(e.getMessage(), e);
        throw aBankingException;
    } finally {
        aSession.flush();
        aSession.clear();
    }
    return returnStatus;
}

From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java

License:Open Source License

@Override
public boolean updateDepositAndWithDraw(MoAccount theMoaccount, Session aSession) throws BankingException {
    //Session aSession = itsSessionFactory.openSession();
    MoAccount aMoaccount = null;// ww w .  j  a va 2  s  .c  o m
    try {
        aMoaccount = (MoAccount) aSession.get(MoAccount.class, theMoaccount.getMoAccountId());
        if (theMoaccount.getOper().equals("delete") || theMoaccount.getOper().equals("void")) {
            if (theMoaccount.getMoTransactionTypeId() == 0) {
                aMoaccount.setSubtractions(aMoaccount.getSubtractions()
                        .add(theMoaccount.getSubtractions().multiply(new BigDecimal(-1))));
            } else {
                aMoaccount.setAdditions(aMoaccount.getAdditions().add(theMoaccount.getAdditions()));
            }
        } else {
            if (theMoaccount.getMoTransactionTypeId() == 0) {
                aMoaccount.setAdditions(aMoaccount.getAdditions().add(theMoaccount.getAdditions()));
            } else {
                aMoaccount.setSubtractions(aMoaccount.getSubtractions()
                        .add(theMoaccount.getSubtractions().multiply(new BigDecimal(-1))));
            }
        }
        aSession.update(aMoaccount);
    } catch (Exception e) {
        itsLogger.error(e.getMessage(), e);
        BankingException aBankingException = new BankingException(e.getMessage(), e);
        throw aBankingException;
    } finally {
        aSession.flush();
        aSession.clear();
    }
    return true;
}

From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java

License:Open Source License

@Override
public boolean saveGlmultipleAccount1(Momultipleaccount momulaccount, Session aMomulAccountSession)
        throws BankingException {
    try {//from   ww  w .j ava2 s .c o m
        aMomulAccountSession.save(momulaccount);
    } catch (Exception excep) {
        itsLogger.error(excep.getMessage(), excep);
        BankingException aBankingException = new BankingException(excep.getMessage(), excep);
        throw aBankingException;
    } finally {
        aMomulAccountSession.flush();
        aMomulAccountSession.clear();
    }
    return true;
}

From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java

License:Open Source License

@Override
public boolean updateGlmultipleAccount1(Momultipleaccount momulacc, Session aSession) throws BankingException {
    Momultipleaccount aMomulaccount = null;
    try {//  w w  w  .j a v  a  2 s  .c o m
        itsLogger.info("Momultiaccountid==" + momulacc.getMoMultipleAccountsId());
        aMomulaccount = (Momultipleaccount) aSession.get(Momultipleaccount.class,
                momulacc.getMoMultipleAccountsId());
        aMomulaccount.setMoTransactionId(momulacc.getMoTransactionId());
        aMomulaccount.setAmount(momulacc.getAmount());
        aMomulaccount.setCoAccountId(momulacc.getCoAccountId());
        aSession.update(aMomulaccount);
    } catch (Exception e) {
        e.printStackTrace();
        itsLogger.error(e.getMessage(), e);
        BankingException aBankingException = new BankingException(e.getMessage(), e);
        throw aBankingException;
    } finally {
        aSession.flush();
        aSession.clear();
    }
    return true;
}

From source file:com.utils.dao.impl.ChitdaoImpl.java

public boolean save(Object object, List list) throws Exception {
    boolean flag = false;
    Session session = HBSession.getSessionFactory().openSession();
    try {//from  ww w  .java  2  s.  c o  m
        session.beginTransaction();
        session.persist(object);
        int i = 0;
        for (Object element : list) {
            if (element != null) {
                session.save(element);
            }
            if (i == (list.size() / 2)) {
                session.flush();
                session.clear();
            }
            i++;
        }
        session.getTransaction().commit();
        flag = true;
    } catch (Exception e) {
        e.printStackTrace();
        flag = false;
        session.getTransaction().rollback();
    }
    session.close();
    return flag;
}

From source file:com.utils.dao.impl.ChitdaoImpl.java

public boolean save(List list) throws Exception {
    boolean flag = false;
    Session session = HBSession.getSessionFactory().openSession();
    try {/*from ww  w. j a v a  2s .c o m*/
        session.beginTransaction();
        int i = 0;
        for (Object element : list) {
            if (element != null) {
                session.save(element);
            }
            if (i == (list.size() / 2)) {
                session.flush();
                session.clear();
            }
            i++;
        }
        session.getTransaction().commit();
        flag = true;
    } catch (Exception e) {
        e.printStackTrace();
        flag = false;
        session.getTransaction().rollback();
    }
    session.close();
    return flag;
}

From source file:com.viettel.logistic.wms.dao.CellsDAO.java

License:Open Source License

/**
 * NgocND6 insert list cell using import excel
 * @param lstCell/*from  w ww. j  av a 2 s . com*/
 * @param stockID
 * @return 
 */
public ResultDTO insertListCells(List<Cells> lstCell, String stockID) {
    Session openSession;
    openSession = sessionFactory.openSession();
    Transaction tx = openSession.beginTransaction();
    ResultDTO result = new ResultDTO();
    Cells cells = null;
    String lstCellsId = "";
    try {
        for (int i = 0; i < lstCell.size(); i++) {
            cells = lstCell.get(i);
            lstCellsId = lstCellsId + "," + cells.getCode();
            openSession.save(cells);
            if (i % 50 == 0) { // Same as the JDBC batch size
                //flush a batch of inserts and release memory:
                openSession.flush();
                openSession.clear();
                lstCellsId = "";
            }
        }
        tx.commit();
        result.setMessage(ParamUtils.SUCCESS);
    } catch (HibernateException ex) {

        if (ex.getCause() != null && ex.getCause() instanceof SQLException) {
            SQLException se = (SQLException) ex.getCause();
            if (se.getErrorCode() == 1) {
                openSession.clear();
                ConditionBean condition = new ConditionBean("code", ParamUtils.OP_IN,
                        lstCellsId.replaceFirst(",", ""), ParamUtils.TYPE_STRING);
                ConditionBean condition1 = new ConditionBean("stockId", ParamUtils.OP_EQUAL,
                        String.valueOf(stockID), ParamUtils.TYPE_NUMBER);
                List<ConditionBean> lstConditionBeans = new ArrayList<>();
                lstConditionBeans.add(condition);
                lstConditionBeans.add(condition1);
                List<Cells> lstCellsViolated = findSession("Cells", lstConditionBeans, "code", 0,
                        Integer.MAX_VALUE, null, getSession());
                if (lstCellsViolated != null && !lstCellsViolated.isEmpty()) {
                    String id = "";
                    for (Cells item : lstCellsViolated) {
                        id = id + "," + item.getCode();
                    }
                    result.setKey(id.replaceFirst(",", ""));
                }
            }
        }
        tx.rollback();
        result.setMessage(ParamUtils.FAIL);
    } finally {
        openSession.close();
    }

    return result;
}

From source file:com.viettel.logistic.wms.dao.GoodsDAO.java

License:Open Source License

public ResultDTO insertListGoods(List<Goods> lstGoods) {
    ResultDTO resultDTO = new ResultDTO();
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    ResultDTO result = new ResultDTO();
    Goods goods = null;//from  ww w .ja v  a 2s  .  c  om
    String lstGoodsId = "";
    long cusID = lstGoods.get(0).getCustId();
    try {
        for (int i = 0; i < lstGoods.size(); i++) {
            goods = lstGoods.get(i);
            lstGoodsId = lstGoodsId + "," + goods.getCode();
            session.save(goods);
            if (i % 50 == 0) { // Same as the JDBC batch size
                //flush a batch of inserts and release memory:
                session.flush();
                session.clear();
                lstGoodsId = "";
            }
        }
        tx.commit();
        result.setMessage(ParamUtils.SUCCESS);
    } catch (HibernateException ex) {

        if (ex.getCause() != null && ex.getCause() instanceof SQLException) {
            SQLException se = (SQLException) ex.getCause();
            //                Transaction tx2 = session.beginTransaction();
            if (se.getErrorCode() == 1) {
                session.clear();
                ConditionBean condition = new ConditionBean("code", ParamUtils.OP_IN,
                        lstGoodsId.replaceFirst(",", ""), ParamUtils.TYPE_STRING);
                ConditionBean condition1 = new ConditionBean("custId", ParamUtils.OP_EQUAL,
                        String.valueOf(cusID), ParamUtils.TYPE_NUMBER);
                List<ConditionBean> lstConditionBeans = new ArrayList<>();
                lstConditionBeans.add(condition);
                lstConditionBeans.add(condition1);
                List<Goods> lstGoodsViolated = findSession("Goods", lstConditionBeans, "code", 0,
                        Integer.MAX_VALUE, null, getSession());
                if (lstGoodsViolated != null && !lstGoodsViolated.isEmpty()) {
                    String id = "";
                    for (Goods item : lstGoodsViolated) {
                        id = id + "," + item.getCode();
                    }
                    result.setKey(id.replaceFirst(",", ""));
                }
            }
        }
        tx.rollback();
        result.setMessage(ParamUtils.FAIL);
    } finally {
        session.close();
    }

    return result;
}

From source file:com.xpn.xwiki.store.migration.hibernate.R40000XWIKI6990DataMigration.java

License:Open Source License

@Override
public void hibernateMigrate() throws DataMigrationException, XWikiException {
    final Map<Long, Long> docs = new HashMap<Long, Long>();
    final List<String> customMappedClasses = new ArrayList<String>();
    final Map<Long, Long> objs = new HashMap<Long, Long>();
    final Queue<Map<Long, Long>> stats = new LinkedList<Map<Long, Long>>();

    // Get ids conversion list
    getStore().executeRead(getXWikiContext(), new HibernateCallback<Object>() {
        private void fillDocumentIdConversion(Session session, Map<Long, Long> map) {
            String database = getXWikiContext().getWikiId();
            @SuppressWarnings("unchecked")
            List<Object[]> results = session
                    .createQuery("select doc.id, doc.space, doc.name, doc.defaultLanguage, doc.language from "
                            + XWikiDocument.class.getName() + " as doc")
                    .list();/*from  www  . ja  va2s  .  c  o  m*/

            for (Object[] result : results) {
                long oldId = (Long) result[0];
                String space = (String) result[1];
                String name = (String) result[2];
                String defaultLanguage = (String) result[3];
                String language = (String) result[4];

                // Use a real document, since we need the language to be appended.
                // TODO: Change this when the locale is integrated
                XWikiDocument doc = new XWikiDocument(new DocumentReference(database, space, name));
                doc.setDefaultLanguage(defaultLanguage);
                doc.setLanguage(language);
                long newId = doc.getId();

                if (oldId != newId) {
                    map.put(oldId, newId);
                }
            }

            logProgress("Retrieved %d document IDs to be converted.", map.size());
        }

        private void fillObjectIdConversion(Session session, Map<Long, Long> map) {
            @SuppressWarnings("unchecked")
            List<Object[]> results = session
                    .createQuery("select obj.id, obj.name, obj.className, obj.number from "
                            + BaseObject.class.getName() + " as obj")
                    .list();
            for (Object[] result : results) {
                long oldId = (Long) result[0];
                String docName = (String) result[1];
                String className = (String) result[2];
                Integer number = (Integer) result[3];

                BaseObjectReference objRef = new BaseObjectReference(
                        R40000XWIKI6990DataMigration.this.resolver.resolve(className), number,
                        R40000XWIKI6990DataMigration.this.resolver.resolve(docName));
                long newId = Util.getHash(R40000XWIKI6990DataMigration.this.serializer.serialize(objRef));

                if (oldId != newId) {
                    map.put(oldId, newId);
                }
            }

            logProgress("Retrieved %d object IDs to be converted.", map.size());
        }

        private void fillCustomMappingMap(XWikiHibernateStore store, XWikiContext context)
                throws XWikiException {
            processCustomMappings(store, new CustomMappingCallback() {
                @Override
                public void processCustomMapping(XWikiHibernateStore store, String name, String mapping,
                        boolean hasDynamicMapping) throws XWikiException {
                    if (INTERNAL.equals(mapping) || hasDynamicMapping) {
                        customMappedClasses.add(name);
                    }
                }
            }, context);

            logProgress("Retrieved %d custom mapped classes to be processed.", customMappedClasses.size());
        }

        private void fillStatsConversionMap(Session session, Class<?> klass, Map<Long, Long> map) {
            @SuppressWarnings("unchecked")
            List<Object[]> results = session
                    .createQuery(
                            "select stats.id, stats.name, stats.number from " + klass.getName() + " as stats")
                    .list();
            for (Object[] result : results) {
                long oldId = (Long) result[0];
                String statsName = (String) result[1];
                Integer number = (Integer) result[2];

                // Do not try to convert broken records which would cause duplicated ids
                if (statsName != null && !statsName.startsWith(".") && !statsName.endsWith(".")) {
                    long newId = R40000XWIKI6990DataMigration.this.statsIdComputer.getId(statsName, number);

                    if (oldId != newId) {
                        map.put(oldId, newId);
                    }
                } else {
                    logger.debug("Skipping invalid statistical entry [{}] with name [{}]", oldId, statsName);
                }
            }

            String klassName = klass.getName().substring(klass.getName().lastIndexOf('.') + 1);
            logProgress("Retrieved %d %s statistics IDs to be converted.", map.size(),
                    klassName.substring(0, klassName.length() - 5).toLowerCase());
        }

        @Override
        public Object doInHibernate(Session session) throws XWikiException {
            try {
                fillDocumentIdConversion(session, docs);

                fillObjectIdConversion(session, objs);

                // Retrieve custom mapped classes
                if (getStore() instanceof XWikiHibernateStore) {
                    fillCustomMappingMap((XWikiHibernateStore) getStore(), getXWikiContext());
                }

                // Retrieve statistics ID conversion
                for (Class<?> statsClass : STATS_CLASSES) {
                    Map<Long, Long> map = new HashMap<Long, Long>();
                    fillStatsConversionMap(session, statsClass, map);
                    stats.add(map);
                }

                session.clear();
            } catch (Exception e) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                        XWikiException.ERROR_XWIKI_STORE_MIGRATION, getName() + " migration failed", e);
            }
            return null;
        }
    });

    // Cache the configuration and the dialect
    configuration = getStore().getConfiguration();
    dialect = configuration.buildSettings().getDialect();

    // Check configuration for safe mode
    XWikiConfig config = getXWikiContext().getWiki().getConfig();
    /* True if migration should use safe but slower non-bulk native updates. */
    boolean useSafeUpdates = "1"
            .equals(config.getProperty("xwiki.store.migration." + this.getName() + ".safemode", "0"));

    // Use safe mode if the database has no temporary table supported by hibernate
    useSafeUpdates = useSafeUpdates || !configuration.buildSettings().getDialect().supportsTemporaryTables();

    // Proceed to document id conversion
    if (!docs.isEmpty()) {
        if (!useSafeUpdates) {
            // Pair table,key for table that need manual updates
            final List<String[]> tableToProcess = new ArrayList<String[]>();

            for (Class<?> docClass : DOC_CLASSES) {
                tableToProcess.addAll(getAllTableToProcess(docClass.getName()));
            }
            for (Class<?> docClass : DOCLINK_CLASSES) {
                tableToProcess.addAll(getAllTableToProcess(docClass.getName(), "docId"));
            }

            logProgress("Converting %d document IDs in %d tables...", docs.size(), tableToProcess.size());

            final long[] times = new long[tableToProcess.size() + 1];
            try {
                getStore().executeWrite(getXWikiContext(), new AbstractBulkIdConversionHibernateCallback() {
                    @Override
                    public void doBulkIdUpdate() {
                        times[timer++] += insertIdUpdates(docs);

                        for (String[] table : tableToProcess) {
                            times[timer++] += executeSqlIdUpdate(table[0], table[1]);
                        }
                    }
                });
            } catch (Exception e) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                        XWikiException.ERROR_XWIKI_STORE_MIGRATION, getName() + " migration failed", e);
            }
            if (logger.isDebugEnabled()) {
                int timer = 0;
                logger.debug("Time elapsed for inserts: {} ms", times[timer++] / 1000000);

                for (String[] table : tableToProcess) {
                    logger.debug("Time elapsed for {} table: {} ms", table[0], times[timer++] / 1000000);
                }
            }
        } else {
            final List<String[]> docsColl = new ArrayList<String[]>();
            for (Class<?> docClass : DOC_CLASSES) {
                docsColl.addAll(getCollectionProperties(getClassMapping(docClass.getName())));
            }
            for (Class<?> docClass : DOCLINK_CLASSES) {
                docsColl.addAll(getCollectionProperties(getClassMapping(docClass.getName())));
            }

            logProgress("Converting %d document IDs in %d tables and %d collection tables...", docs.size(),
                    DOC_CLASSES.length + DOCLINK_CLASSES.length, docsColl.size());

            final long[] times = new long[DOC_CLASSES.length + DOCLINK_CLASSES.length + docsColl.size()];
            convertDbId(docs, new AbstractIdConversionHibernateCallback() {
                @Override
                public void doSingleUpdate() {
                    for (String[] coll : docsColl) {
                        times[timer++] += executeSqlIdUpdate(coll[0], coll[1]);
                    }

                    for (Class<?> doclinkClass : DOCLINK_CLASSES) {
                        times[timer++] += executeIdUpdate(doclinkClass, DOCID);
                    }
                    times[timer++] += executeIdUpdate(XWikiLink.class, DOCID);
                    times[timer++] += executeIdUpdate(XWikiRCSNodeInfo.class, ID + '.' + DOCID);
                    times[timer++] += executeIdUpdate(XWikiDocument.class, ID);
                }
            });
            if (logger.isDebugEnabled()) {
                int timer = 0;
                for (String[] coll : docsColl) {
                    logger.debug("Time elapsed for {} collection: {} ms", coll[0], times[timer++] / 1000000);
                }
                for (Class<?> doclinkClass : DOCLINK_CLASSES) {
                    logger.debug("Time elapsed for {} class: {} ms", doclinkClass.getName(),
                            times[timer++] / 1000000);
                }
                logger.debug("Time elapsed for {} class: {} ms", XWikiRCSNodeInfo.class.getName(),
                        times[timer++] / 1000000);
                logger.debug("Time elapsed for {} class: {} ms", XWikiDocument.class.getName(),
                        times[timer++] / 1000000);
            }
        }
        logProgress("All document IDs has been converted successfully.");
    } else {
        logProgress("No document IDs to convert, skipping.");
    }

    // Proceed to object id conversion
    if (!objs.isEmpty()) {
        if (!useSafeUpdates) {
            // Pair table,key for table that need manual updates
            final List<String[]> tableToProcess = new ArrayList<String[]>();

            PersistentClass objklass = getClassMapping(BaseObject.class.getName());
            tableToProcess.addAll(getCollectionProperties(objklass));

            for (Class<?> propertyClass : PROPERTY_CLASS) {
                tableToProcess.addAll(getAllTableToProcess(propertyClass.getName()));
            }
            for (String customClass : customMappedClasses) {
                tableToProcess.addAll(getAllTableToProcess(customClass));
            }
            tableToProcess.add(new String[] { objklass.getTable().getName(), getKeyColumnName(objklass) });

            logProgress("Converting %d object IDs in %d tables...", objs.size(), tableToProcess.size());

            final long[] times = new long[tableToProcess.size() + 1];
            try {
                getStore().executeWrite(getXWikiContext(), new AbstractBulkIdConversionHibernateCallback() {
                    @Override
                    public void doBulkIdUpdate() {
                        times[timer++] += insertIdUpdates(objs);

                        for (String[] table : tableToProcess) {
                            times[timer++] += executeSqlIdUpdate(table[0], table[1]);
                        }
                    }
                });
            } catch (Exception e) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                        XWikiException.ERROR_XWIKI_STORE_MIGRATION, getName() + " migration failed", e);
            }
            if (logger.isDebugEnabled()) {
                int timer = 0;
                logger.debug("Time elapsed for inserts: {} ms", times[timer++] / 1000000);

                for (String[] table : tableToProcess) {
                    logger.debug("Time elapsed for {} table: {} ms", table[0], times[timer++] / 1000000);
                }
            }
        } else {
            // Name of classes that need manual updates
            final List<String> classToProcess = new ArrayList<String>();
            // Name of custom classes that need manual updates
            final List<String> customClassToProcess = new ArrayList<String>();
            // Pair table,key for collection table that need manual updates
            final List<String[]> objsColl = new ArrayList<String[]>();

            objsColl.addAll(getCollectionProperties(getClassMapping(BaseObject.class.getName())));
            for (Class<?> propertyClass : PROPERTY_CLASS) {
                String className = propertyClass.getName();
                PersistentClass klass = getClassMapping(className);

                // Add collection table that will not be updated by cascaded updates
                objsColl.addAll(getCollectionProperties(klass));

                // Skip classes that will be updated by cascaded updates
                if (!this.fkTables.contains(klass.getTable())) {
                    classToProcess.add(className);
                }
            }
            for (String customClass : customMappedClasses) {
                PersistentClass klass = getClassMapping(customClass);

                // Add collection table that will not be updated by cascaded updates
                objsColl.addAll(getCollectionProperties(klass));

                // Skip classes that will be updated by cascaded updates
                if (!this.fkTables.contains(klass.getTable())) {
                    customClassToProcess.add(customClass);
                }
            }

            logProgress(
                    "Converting %d object IDs in %d tables, %d custom mapped tables and %d collection tables...",
                    objs.size(), classToProcess.size() + 1, customClassToProcess.size(), objsColl.size());

            final long[] times = new long[classToProcess.size() + 1 + customClassToProcess.size()
                    + objsColl.size()];
            convertDbId(objs, new AbstractIdConversionHibernateCallback() {
                @Override
                public void doSingleUpdate() {
                    for (String[] coll : objsColl) {
                        times[timer++] += executeSqlIdUpdate(coll[0], coll[1]);
                    }

                    for (String customMappedClass : customClassToProcess) {
                        times[timer++] += executeIdUpdate(customMappedClass, ID);
                    }

                    for (String propertyClass : classToProcess) {
                        times[timer++] += executeIdUpdate(propertyClass, IDID);
                    }

                    times[timer++] += executeIdUpdate(BaseObject.class, ID);
                }
            });
            if (logger.isDebugEnabled()) {
                int timer = 0;
                for (String[] coll : objsColl) {
                    logger.debug("Time elapsed for {} collection: {} ms", coll[0], times[timer++] / 1000000);
                }
                for (String customMappedClass : customClassToProcess) {
                    logger.debug("Time elapsed for {} custom table: {} ms", customMappedClass,
                            times[timer++] / 1000000);
                }
                for (String propertyClass : classToProcess) {
                    logger.debug("Time elapsed for {} property table: {} ms", propertyClass,
                            times[timer++] / 1000000);
                }
                logger.debug("Time elapsed for {} class: {} ms", BaseObject.class.getName(),
                        times[timer++] / 1000000);
            }
        }
        logProgress("All object IDs has been converted successfully.");
    } else {
        logProgress("No object IDs to convert, skipping.");
    }

    // Proceed to statistics id conversions
    for (final Class<?> statsClass : STATS_CLASSES) {

        Map<Long, Long> map = stats.poll();
        String klassName = statsClass.getName().substring(statsClass.getName().lastIndexOf('.') + 1);
        klassName = klassName.substring(0, klassName.length() - 5).toLowerCase();

        if (!map.isEmpty()) {
            if (!useSafeUpdates) {
                final List<String[]> tableToProcess = new ArrayList<String[]>();
                final Map<Long, Long> statids = map;

                PersistentClass statklass = getClassMapping(statsClass.getName());
                tableToProcess.addAll(getCollectionProperties(statklass));
                tableToProcess
                        .add(new String[] { statklass.getTable().getName(), getKeyColumnName(statklass) });

                logProgress("Converting %d %s statistics IDs in %d tables...", map.size(), klassName,
                        tableToProcess.size());

                final long[] times = new long[tableToProcess.size() + 1];
                try {
                    getStore().executeWrite(getXWikiContext(), new AbstractBulkIdConversionHibernateCallback() {
                        @Override
                        public void doBulkIdUpdate() {
                            times[timer++] += insertIdUpdates(statids);

                            for (String[] table : tableToProcess) {
                                times[timer++] += executeSqlIdUpdate(table[0], table[1]);
                            }
                        }
                    });
                } catch (Exception e) {
                    throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                            XWikiException.ERROR_XWIKI_STORE_MIGRATION, getName() + " migration failed", e);
                }
                if (logger.isDebugEnabled()) {
                    int timer = 0;
                    logger.debug("Time elapsed for inserts: {} ms", times[timer++] / 1000000);

                    for (String[] table : tableToProcess) {
                        logger.debug("Time elapsed for {} table: {} ms", table[0], times[timer++] / 1000000);
                    }
                }
            } else {
                final List<String[]> statsColl = new ArrayList<String[]>();
                statsColl.addAll(getCollectionProperties(getClassMapping(statsClass.getName())));

                logProgress("Converting %d %s statistics IDs in 1 tables and %d collection tables...",
                        map.size(), klassName, statsColl.size());

                final long[] times = new long[statsColl.size() + 1];
                convertDbId(map, new AbstractIdConversionHibernateCallback() {
                    @Override
                    public void doSingleUpdate() {
                        for (String[] coll : statsColl) {
                            times[timer++] += executeSqlIdUpdate(coll[0], coll[1]);
                        }
                        times[timer++] += executeIdUpdate(statsClass, ID);
                    }
                });
                if (logger.isDebugEnabled()) {
                    int timer = 0;
                    for (String[] coll : statsColl) {
                        logger.debug("Time elapsed for {} collection: {} ms", coll[0],
                                times[timer++] / 1000000);
                    }
                    logger.debug("Time elapsed for {} class: {} ms", statsClass.getName(),
                            times[timer++] / 1000000);
                }
            }
            logProgress("All %s statistics IDs has been converted successfully.", klassName);
        } else {
            logProgress("No %s statistics IDs to convert, skipping.", klassName);
        }
    }
}

From source file:com.yahoo.elide.datastores.hibernate5.HibernateEntityManagerStore.java

License:Apache License

/**
 * Start Hibernate transaction.//from  www. j a  v a 2  s  .  c  o m
 *
 * @return transaction
 */
@Override
@SuppressWarnings("resource")
public DataStoreTransaction beginTransaction() {
    Session session = getSession();
    session.beginTransaction();
    session.clear();
    return transactionSupplier.get(session, isScrollEnabled, scrollMode);
}