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.mss.mirage.util.HibernateDataProvider.java

License:Open Source License

public Map getGreenSheetPaymentTerms(String greenSheetPaymentTermskey) throws ServiceLocatorException {

    Map greenSheetPaymentTermsMap = new TreeMap();//key-Description

    if (CacheManager.getCache().containsKey(greenSheetPaymentTermskey)) {
        greenSheetPaymentTermsMap = (Map) CacheManager.getCache().get(greenSheetPaymentTermskey);
    } else {// w  ww .j  a  va2 s  .co m
        //getting sessionFactory for the HibernateUtil class.
        Session session = HibernateServiceLocator.getInstance().getSession();

        //Genarating a quary for retrieving the data from the database.
        String SQL_STG = "select tp.bdmID,tp.description from CrmGreenSheetPaymentTermsData as tp";
        Query query = session.createQuery(SQL_STG);
        for (Iterator it = query.iterate(); it.hasNext();) {
            Object[] row = (Object[]) it.next();
            //Storing values into the TreeMap.
            greenSheetPaymentTermsMap.put(row[0].toString(), row[1].toString());

        } // closing for loop.

        session.clear();
        CacheManager.getCache().put(greenSheetPaymentTermskey, greenSheetPaymentTermsMap);

        // Closing hibernate session
        try {
            // Closing hibernate session
            session.close();
            session = null;
        } catch (HibernateException he) {
            throw new ServiceLocatorException(he);
        } finally {
            if (session != null) {
                try {
                    session.close();
                    session = null;
                } catch (HibernateException he) {
                    throw new ServiceLocatorException(he);
                }
            }
        }

    } // closing if condition.

    return greenSheetPaymentTermsMap;// returning the object.
}

From source file:com.mycompany.gmailtest.dao.MessageDao.java

public void addMessages(List<Message> messages) {
    try {/*from  w  ww .  j  a  va  2  s. c o m*/
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        for (int i = 0; i < messages.size(); i++) {
            Message message = messages.get(i);
            session.save(message);
            if (i % 100 == 0) {
                session.flush();
                session.clear();
            }
        }
        tx.commit();
        session.close();
    } catch (Exception e) {
        throw e;
    }
}

From source file:com.nec.crud.hibernate.HibernateSessionManager.java

License:Open Source License

/**
 * ?//from  w w w.j a v  a 2  s  . c o m
 * 
 * this is VERY IMPORTANT so that the transaction is commited
 * and the session finalized.
 */
public static void closeSession(Session session) {
    if (session != null && session.isOpen()) {
        session.clear();

        // Perform actual closing of the Hibernate Session, catching and
        // logging any cleanup exceptions thrown.
        SessionFactoryUtils.closeSession(session);
    }
}

From source file:com.nec.crud.hibernate4.HibernateSessionManager.java

License:Open Source License

/**
 * ?//from w  ww.  j a  va  2  s . c  o m
 * 
 * this is VERY IMPORTANT so that the transaction is commited
 * and the session finalized.
 */
public static void disconnectAll() {
    final Session session = SESSIONS.get();
    if (session != null && session.isOpen()) {
        session.clear();

        // Perform actual closing of the Hibernate Session, catching and
        // logging any cleanup exceptions thrown.
        SessionFactoryUtils.closeSession(session);
    }
    SESSIONS.remove();
    SESSIONS.set(null);
}

From source file:com.nextep.datadesigner.vcs.services.VersionHelper.java

License:Open Source License

/**
 * Executes the specified revision-check query for the given element id. The return boolean
 * indicates whether the revision number fetched from the database through the given query
 * matches the expected revision number.
 * /*from   w  w w  .  j  a  v a 2 s  .co m*/
 * @param query SQL query which can retrieve the revision number from its ID
 * @param id unique ID of element to check the revision
 * @param expectedRevision expected revision number
 * @return <code>true</code> if the expected revision number matches the repository revision
 *         number, else <code>false</code>
 */
private static boolean queryIsUpToDate(String query, long id, long expectedRevision) {
    final Session session = HibernateUtil.getInstance().getSandBoxSession();
    session.flush();
    session.clear();
    SQLQuery sqlQuery = session.createSQLQuery(query);
    sqlQuery.setLong(0, id);
    Number revision = (Number) sqlQuery.uniqueResult();
    return revision == null || (revision != null && revision.longValue() == expectedRevision);
}

From source file:com.nkapps.billing.dao.BankStatementDaoImpl.java

@Override
public int saveBankStatements(List<BankStatement> bsList) throws Exception {
    int errorCount = 0;

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Session session = getSession();
    Transaction transaction = session.beginTransaction();

    int itr = 0;/*w  w w. ja v  a  2s.c om*/
    for (BankStatement bs : bsList) {
        itr++;
        Short transferable = 0;
        String transferableProps = null;
        Short transfered = 0;
        try {

            Set<String> fizTins = findFizTins(bs.getPaymentDetails());
            String yurTin = findYurTin(bs.getPaymentDetails());

            if (yurTin != null && !bs.getTin().equals(yurTin) && !isFizTin(bs.getTin()) && fizTins.isEmpty()) {
                transfered = -1; // 3 -litso
                throw new Exception("bank statement is payment detail yur tin not allowed");
            }

            if (bs.getPaymentDetails().indexOf("$MUNIS$") > 0) {
                String tin = fizTins.iterator().next();
                Payment payment = paymentDao.findPayment(tin, bs.getPaymentNum(), bs.getPaymentDate(),
                        bs.getPaymentSum(), bs.getTin(), (short) 2); // munis payment to searching
                if (payment != null) {
                    transfered = 2; // already transfered by munis
                    BankStatementMunis bsm = new BankStatementMunis();
                    BankStatementMunisId bsmId = new BankStatementMunisId();
                    bsmId.setBankStatement(bs);
                    bsmId.setMunis(payment.getMunisPayment().getId().getMunis());
                    bsm.setId(bsmId);

                    session.save(bsm);

                    throw new Exception("bank statement is already inserted by munis");
                }
            }

            if (("fake tin").equals(bs.getTin()) && bs.getPaymentDetails().indexOf("CLICK") > 0) {

                transferable = 5;

            } else if (("fake tin").equals(bs.getTin()) && bs.getPaymentDetails().indexOf("CMC") > 0) {

                transferable = 6;

            } else {
                boolean isClaim = isClaim(session, bs);

                if (fizTins != null && !fizTins.isEmpty()) {
                    if (isClaim) { // Trebovaniya
                        String tin = fizTins.iterator().next(); // tolko dlya odin fiz inn

                        transferable = 1;
                        transferableProps = tin;

                    } else {

                        transferable = 2;
                        transferableProps = StringUtils.join(fizTins, ",");

                    }
                } else if (isClaim) { // Trebovaniya

                    transferable = 3;
                    transferableProps = yurTin;

                } else {

                    transferable = 4;
                    transferableProps = yurTin;

                }
            }

        } catch (Exception e) {
            // bank statement is not transferable
        }

        Set<ConstraintViolation<BankStatement>> constraints = validator.validate(bs);
        if (constraints.isEmpty()) {

            BankStatement bsPersisted = (BankStatement) session.get(BankStatement.class, bs.getId());
            if (bsPersisted == null) {
                bs.setTransferable(transferable);
                bs.setTransferableProps(transferableProps);
                bs.setTransfered(transfered); // only when on saving
                bs.setReturnState((short) 0); // only when on saving

                session.save(bs);
            } else {
                bsPersisted.setTin(bs.getTin());
                bsPersisted.setName(bs.getName());
                bsPersisted.setMfo(bs.getMfo());
                bsPersisted.setChet(bs.getChet());
                bsPersisted.setPaymentNum(bs.getPaymentNum());
                bsPersisted.setPaymentDate(bs.getPaymentDate());
                bsPersisted.setPaymentSum(bs.getPaymentSum());
                bsPersisted.setPaymentDetails(bs.getPaymentDetails());

                bsPersisted.setTransferable(transferable);
                bsPersisted.setTransferableProps(transferableProps);

                bsPersisted.setIssuerSerialNumber(bs.getIssuerSerialNumber());
                bsPersisted.setIssuerIp(bs.getIssuerIp());
                bsPersisted.setDateUpdated(bs.getDateUpdated());

                session.update(bsPersisted);
            }
            if (itr % 500 == 0) {
                session.flush();
                session.clear();
            }
        } else {
            errorCount++;
            logger.error("Error on saving, tin = " + bs.getTin());
        }
    }
    transaction.commit();
    session.close();

    return errorCount;
}

From source file:com.nkapps.billing.dao.BankStatementDaoImpl.java

@Override
public void saveToPayment() throws Exception {
    List<BankStatement> bsList;
    Session sessionQuery = getSession();

    String q = " SELECT " + "  b " + " FROM BankStatement b" + " WHERE b.transferable IN (1,2,3,4) "
            + " AND b.transfered = 0 " + " AND b.bankStatementPayments IS EMPTY ";
    Query query = sessionQuery.createQuery(q);
    bsList = query.list();/*from w  ww  .  j  av  a 2s .  co  m*/

    sessionQuery.close();
    sessionQuery = getSession();

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    if (bsList != null) {
        LocalDateTime dateTime = LocalDateTime.now();

        Session sessionTransaction = getSession();
        Transaction transaction = sessionTransaction.beginTransaction();
        int itr = 0;
        for (BankStatement bs : bsList) {
            itr++;
            try {
                transferBankStatementToPayment(sessionQuery, sessionTransaction, validator, bs, dateTime);

                if (itr % 500 == 0) {
                    sessionTransaction.flush();
                    sessionTransaction.clear();
                }
            } catch (Exception e) {
                logger.error("Error on payment saving: exception = " + e.getMessage() + ", bank_statement_id: "
                        + bs.getId());
            }
        }
        transaction.commit();
        sessionTransaction.close();

    }
    sessionQuery.close();
}

From source file:com.nkapps.billing.dao.BankStatementDaoImpl.java

@Override
public void updateInvoiceNums(Integer year) throws Exception {
    Session sessionQuery = getSession();
    InvoiceNum in = (InvoiceNum) sessionQuery.get(InvoiceNum.class, year);
    if (in == null) {
        in = new InvoiceNum(year);
        in.setNum(0l);//from  w w w.j  av a  2  s  .  c om
    }

    Long num = in.getNum();

    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy H:m:s.S");
    Date paymentDateBegin = sdf.parse("01.01." + year + " 00:00:00.000");
    Date paymentDateEnd = sdf.parse("31.12." + year + " 23:59:59.999");

    String q = " SELECT bs "
            + " FROM BankStatement bs LEFT JOIN FETCH bs.bankStatementPayments bsp LEFT JOIN FETCH bsp.id.payment p"
            + " WHERE bs.paymentDate BETWEEN :paymentDateBegin" + " AND :paymentDateEnd"
            + " AND bs.invoiceNum IS NULL" + " ORDER BY bs.paymentDate, bs.paymentSum ";
    Query query = sessionQuery.createQuery(q);
    query.setParameter("paymentDateBegin", paymentDateBegin);
    query.setParameter("paymentDateEnd", paymentDateEnd);
    List<BankStatement> bsList = query.list();

    for (BankStatement bs : bsList) {
        if (bs.getBankStatementPayments().isEmpty()) {
            bs.setInvoiceNum(++num);
        } else {
            boolean isClaim = false;
            for (BankStatementPayment bsp : bs.getBankStatementPayments()) {
                Payment payment = bsp.getId().getPayment();
                if (payment.getClaim() == 1) {
                    isClaim = true;
                    break;
                }
            }
            if (isClaim) {
                query = sessionQuery.createQuery("SELECT MAX(da.id) FROM DsApplication da WHERE tin = :tin")
                        .setParameter("tin", bs.getTin());
                Long dsApplicationId = (Long) query.uniqueResult();
                if (dsApplicationId == null) {
                    bs.setInvoiceNum(++num);
                } else {
                    bs.setInvoiceNum(dsApplicationId); // ds_application id
                }
            } else {
                bs.setInvoiceNum(++num);
            }
        }
    }
    sessionQuery.close();

    Session sessionTransaction = getSession();
    Transaction transaction = sessionTransaction.beginTransaction();

    in.setNum(num);
    sessionTransaction.saveOrUpdate(in);

    int itr = 0;
    for (BankStatement bs : bsList) {
        itr++;
        sessionTransaction.update(bs);
        if (itr % 500 == 0) {
            sessionTransaction.flush();
            sessionTransaction.clear();
        }
    }
    transaction.commit();
    sessionTransaction.close();

}

From source file:com.onlineshopping.util.Main.java

public static void main(String[] args) {
    //       Category cat = new Category(); 
    //       cat.setCatName("Jesus1");

    Customer n = new Customer();

    n.setCustEmail("portiafakude@gmail.com");
    //n.setSd("1999-01-04");
    n.setCustName("firstName");
    n.setCustSurname("ffff");
    n.setCustGender("GFHGFHJ");
    n.setCustPassword("jhghg");
    n.setCustContact("hjfhfghh");
    n.setCustDOB("01/01/2007");

    String to = n.getCustEmail();
    if (n.sendEmail

    ("portiafakude@gmail.com", "Dibongz1@tut", "message to recipients",

            to))//from  w w  w  .  j a va 2s  . com
        System.out.println("email sent successfully");

    else
        System.out.println("Some error occured");

    //       String[] to = {n.getCustEmail()};
    //        if(n.sendEmail
    //        
    //            ("portiafakude@gmail.com",
    //                "Dibongz1@tut", 
    //                "message to recipients", 
    //           
    //                to)) System.out.println("email sent successfully");
    //            
    //                else System.out.println("Some error occured");

    Transaction trns = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        session.save(n);
        session.getTransaction().commit();
    } catch (RuntimeException e) {
        if (trns != null) {
            trns.rollback();
        }
        e.printStackTrace();
    } finally {
        session.clear();
        session.flush();
        session.close();
    }
}

From source file:com.opengamma.security.auditlog.HibernateAuditLogger.java

License:Open Source License

@Override
public void flushCache() {

    List<AuditLogEntry> auditLogCache;
    synchronized (this) {
        auditLogCache = _auditLogCache;/*  w w  w.  ja v  a2 s . com*/
        _auditLogCache = new ArrayList<AuditLogEntry>(_batchSize);
    }

    Session session = getSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        for (int i = 0; i < auditLogCache.size(); i++) {
            AuditLogEntry auditLogEntry = auditLogCache.get(i);
            session.save(auditLogEntry);

            if (i != 0 && i % _batchSize == 0) {
                session.flush();
                session.clear();
            }
        }

        tx.commit();
    } catch (RuntimeException e) {
        // If this happens, for now, assume that there was something wrong 
        // with one of the log messages. Therefore do NOT re-insert 
        // the messages into _auditLogCache.
        s_logger.error("Failed to commit batch to Hibernate", e);
        if (tx != null) {
            tx.rollback();
        }
        throw e;
    } finally {
        session.close();
    }
}