Example usage for org.hibernate Session evict

List of usage examples for org.hibernate Session evict

Introduction

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

Prototype

void evict(Object object);

Source Link

Document

Remove this instance from the session cache.

Usage

From source file:com.trailmagic.image.util.ReplaceImageManifestation.java

License:Open Source License

public void replaceManifestations(final String ownerName, final String rollName, final String importDir) {
    hibernateTemplate.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {
            try {
                User owner = userRepository.getByScreenName(ownerName);
                ImageGroup roll = imageGroupRepository.getRollByOwnerAndName(owner, rollName);
                s_log.info("Processing roll: " + roll.getName());
                for (ImageFrame frame : roll.getFrames()) {
                    Image image = frame.getImage();
                    for (ImageManifestation mf : image.getManifestations()) {

                        String filename = importDir + File.separator + mf.getName();
                        File srcFile = new File(filename);
                        s_log.info("Importing " + srcFile.getPath());
                        if (srcFile.length() > Integer.MAX_VALUE) {
                            s_log.info("File is too big...skipping " + srcFile.getPath());
                            throw new RuntimeException("File too big");
                        }//  w  ww . jav a  2  s .  co m

                        // first read the file to get the size
                        FileInputStream fis = new FileInputStream(srcFile);
                        BufferedImage bi = ImageIO.read(fis);
                        mf.setHeight(bi.getHeight());
                        mf.setWidth(bi.getWidth());
                        s_log.info("New size is " + mf.getHeight() + "x" + mf.getWidth());
                        session.saveOrUpdate(mf);
                        fis.close();

                        fis = new FileInputStream(srcFile);
                        HeavyImageManifestation heavyMf = imfFactory.getHeavyById(mf.getId());
                        heavyMf.setData(Hibernate.createBlob(fis));
                        session.saveOrUpdate(heavyMf);

                        // open the file again to get the size :(

                        s_log.info("ImageManifestation saved: " + heavyMf.getName() + " (" + heavyMf.getId()
                                + ")" + "...flushing session and evicting " + "manifestation.");

                        synchronized (session) {
                            session.flush();
                            session.evict(heavyMf);
                        }

                        // looks like fis has to be open for the flush
                        fis.close();

                    }
                }
            } catch (Exception e) {
                s_log.error("Error replacing manifestations ", e);
            }
            return null;
        }
    });
}

From source file:com.utest.dao.AuditTrailInterceptor.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//ww  w .ja  va  2s .co m
public void postFlush(final Iterator entities) throws CallbackException {
    final Session session = sessionFactory.openSession();

    try {
        while (!logRecords.isEmpty()) {
            final AuditRecord logRecord = logRecords.firstElement();
            logRecords.remove(logRecord);
            if (AuditRecord.INSERT.equals(logRecord.getEventId())) {
                final Integer id = getObjectId(logRecord.getEntityObject());
                if (id != null) {
                    logRecord.setEntityId(getObjectId(logRecord.getEntityObject()));
                    session.save(logRecord);
                } else {
                    session.evict(logRecord);
                }
            } else {
                session.save(logRecord);
            }
        }
    } catch (final HibernateException e) {
        throw new CallbackException(e);
    } finally {
        // logRecords.clear();
        session.flush();
        session.close();
    }

}

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

License:Open Source License

public ResultDTO exportStockGoodsTotal(List<ConditionBean> lstCondition, Double amount, Double amountIssue,
        String changeDate, Session sessions) {
    ///*  w  w w  . j  av  a  2  s  .co m*/
    ResultDTO resultDTO = new ResultDTO();
    String message = ParamUtils.SUCCESS;
    String key = "";
    Double amountUpdate;
    Double amountIssueUpdate;
    //Tim kiem kho hang
    List<StockGoodsTotal> lstStockGoodsTotal = find(model.getModelName(), lstCondition, "", 0, 1, null);
    if (lstStockGoodsTotal != null && lstStockGoodsTotal.size() > 0) {
        //
        resultDTO.setId(lstStockGoodsTotal.get(0).getId().toString());
        //
        amountUpdate = lstStockGoodsTotal.get(0).getAmount() + amount;
        amountIssueUpdate = lstStockGoodsTotal.get(0).getAmountIssue() + amountIssue;
        if (amountUpdate < 0D || amountIssueUpdate < 0D) {
            resultDTO.setMessage(ParamUtils.FAIL);
            resultDTO.setKey(String.valueOf(lstStockGoodsTotal.get(0).getGoodsId()));
            return resultDTO;
        }
        //Set so luong thuc te, dap uang
        lstStockGoodsTotal.get(0).setAmount(amountUpdate);
        lstStockGoodsTotal.get(0).setAmountIssue(amountIssueUpdate);
        try {
            //Set ngay thay doi
            lstStockGoodsTotal.get(0).setChangeDate(DateTimeUtils.convertStringToDate(changeDate));
        } catch (Exception ex) {
            Logger.getLogger(StockGoodsDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        //Luu du lieu: trong cung session lay ban ghi ra de cap nhat thi phai dung save ko dung update
        sessions.evict(lstStockGoodsTotal.get(0));
        updateSession(lstStockGoodsTotal.get(0), sessions);
    } else { //Neu khong tim thay thi tra ve ma loi
        message = ParamUtils.FAIL;
        key = ParamUtils.SYSTEM_OR_DATA_ERROR;
    }

    //Tra ket qua
    resultDTO.setKey(key);
    resultDTO.setMessage(message);
    return resultDTO;
}

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

License:Open Source License

public ResultDTO exportStockGoodsTotalForSyn(List<ConditionBean> lstCondition, Double amount,
        Double amountIssue, String changeDate, Session sessions, StockGoodsTotal stockGoodsTotal) {
    ////from  www .  j  a v a2 s .c  o  m
    ResultDTO resultDTO = new ResultDTO();
    String message = ParamUtils.SUCCESS;
    String key = "";
    Double amountUpdate;
    Double amountIssueUpdate;
    //Tim kiem kho hang
    List<StockGoodsTotal> lstStockGoodsTotal = find(model.getModelName(), lstCondition, "", 0, 1, null);
    if (lstStockGoodsTotal != null && lstStockGoodsTotal.size() > 0) {
        //
        resultDTO.setId(lstStockGoodsTotal.get(0).getId().toString());
        //
        amountUpdate = lstStockGoodsTotal.get(0).getAmount() + amount;
        amountIssueUpdate = lstStockGoodsTotal.get(0).getAmountIssue() + amountIssue;

        //Set so luong thuc te, dap uang
        lstStockGoodsTotal.get(0).setAmount(amountUpdate);
        lstStockGoodsTotal.get(0).setAmountIssue(amountIssueUpdate);
        try {
            //Set ngay thay doi
            lstStockGoodsTotal.get(0).setChangeDate(DateTimeUtils.convertStringToDate(changeDate));
        } catch (Exception ex) {
            Logger.getLogger(StockGoodsDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        //Luu du lieu: trong cung session lay ban ghi ra de cap nhat thi phai dung save ko dung update
        sessions.evict(lstStockGoodsTotal.get(0));
        updateSession(lstStockGoodsTotal.get(0), sessions);
    } else { //Neu khong tim thay thi tra ve ma loi
        //            message = ParamUtils.FAIL;
        //            key = ParamUtils.SYSTEM_OR_DATA_ERROR;
        stockGoodsTotal.setAmount(amount);
        stockGoodsTotal.setAmountIssue(amountIssue);
        sessions.save(stockGoodsTotal);
    }

    //Tra ket qua
    resultDTO.setKey(key);
    resultDTO.setMessage(message);
    return resultDTO;
}

From source file:com.xpn.xwiki.store.XWikiHibernateStore.java

License:Open Source License

/**
 * @deprecated This is internal to XWikiHibernateStore and may be removed in the future.
 *///  ww w.j  a va2s.c o m
@Deprecated
public void deleteXWikiCollection(BaseCollection object, XWikiContext context, boolean bTransaction,
        boolean evict) throws XWikiException {
    if (object == null) {
        return;
    }
    try {
        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(context);
        }
        Session session = getSession(context);

        // Let's check if the class has a custom mapping
        BaseClass bclass = object.getXClass(context);
        List<String> handledProps = new ArrayList<String>();
        if ((bclass != null) && (bclass.hasCustomMapping()) && context.getWiki().hasCustomMappings()) {
            handledProps = bclass.getCustomMappingPropertyList(context);
            Session dynamicSession = session.getSession(EntityMode.MAP);
            Object map = dynamicSession.get(bclass.getName(), Integer.valueOf(object.getId()));
            if (map != null) {
                if (evict) {
                    dynamicSession.evict(map);
                }
                dynamicSession.delete(map);
            }
        }

        if (object.getXClassReference() != null) {
            for (BaseElement property : (Collection<BaseElement>) object.getFieldList()) {
                if (!handledProps.contains(property.getName())) {
                    if (evict) {
                        session.evict(property);
                    }
                    if (session.get(property.getClass(), property) != null) {
                        session.delete(property);
                    }
                }
            }
        }

        // In case of custom class we need to force it as BaseObject to delete the xwikiobject row
        if (!"".equals(bclass.getCustomClass())) {
            BaseObject cobject = new BaseObject();
            cobject.setDocumentReference(object.getDocumentReference());
            cobject.setClassName(object.getClassName());
            cobject.setNumber(object.getNumber());
            if (object instanceof BaseObject) {
                cobject.setGuid(((BaseObject) object).getGuid());
            }
            cobject.setId(object.getId());
            if (evict) {
                session.evict(cobject);
            }
            session.delete(cobject);
        } else {
            if (evict) {
                session.evict(object);
            }
            session.delete(object);
        }

        if (bTransaction) {
            endTransaction(context, true);
        }
    } catch (Exception e) {
        Object[] args = { object.getName() };
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETING_OBJECT,
                "Exception while deleting object {0}", e, args);
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false);
            }
        } catch (Exception e) {
        }
    }
}

From source file:controller.InsertAttendance.java

public static void main(String[] args) {
    //configure cfg xml file
    Configuration cf = new Configuration();
    cf.configure("xmlFiles/hibernate.cfg.xml");

    //build session factory
    SessionFactory sf = cf.buildSessionFactory();
    //get session object
    Session session = sf.openSession();
    //get Transaction object
    Transaction tr = session.beginTransaction();

    //STUDENT ATTANDENCE
    StudentAttendance studentAttendance = new StudentAttendance();

    studentAttendance.setAttendance("P");
    studentAttendance.setLectureDate("20/7/2013");
    studentAttendance.setRollNum("13_CS_19");
    studentAttendance.setTheoryOrPractical("practical");
    studentAttendance.setSubject("BEE");
    studentAttendance.setSemester("2nd");
    studentAttendance.setBatch("13");
    studentAttendance.setDepart("Computer System");
    studentAttendance.setSemesterState("no");

    //INSERT ATTENDANCE OBJECT
    session.save(studentAttendance);//from  w  w w  .  j a v  a 2  s . c  o  m
    tr.commit();
    session.evict(studentAttendance);

    //close session and session factory
    session.close();
    sf.close();

}

From source file:controller2.Driver.java

public static void main(String[] args) {
    //DepartAndBatches table object
    DepartAndBatches db = new DepartAndBatches();
    db.setDepart("CS");
    db.setBatch("17");

    //StudetPersonalInfo table object
    StudentPersonalInfo pInfo = new StudentPersonalInfo();
    pInfo.setBatch("13");
    pInfo.setRollNum("13_CS_19");
    pInfo.setName("imtiaz");
    pInfo.setCnic("44205-82187913");
    pInfo.setFatherName("Sobdar wassan");
    pInfo.setFtContactNum("+923333945719");
    pInfo.setStContactNum("+923002639694");
    pInfo.setGender("Male");
    pInfo.setCaste("wassan");
    pInfo.setTempAdd("Mallir cantt karachi");
    pInfo.setPermAdd("Village Gujh Heran Taulka Sinjhoro District Sanghar");
    pInfo.setStEmail("wassanimtiaz@outlook.com");
    pInfo.setPassword("pakistan");
    pInfo.setBatch("13");
    //Master table object
    Master m = new Master();
    m.setDepart("civil");
    m.setMasterKey("civil");

    //                Master m = new Master();
    //                m.setDepart("Computer");
    //                m.setMasterKey("imtiaz");
    try {/*from   w  w  w .ja  v  a  2 s  .co m*/

        Configuration cf = new Configuration();
        cf.configure("xmlFiles/hibernate.cfg.xml");
        SessionFactory sf = cf.buildSessionFactory();
        // SessionFactory sf = HibernateUtil.getSessionFactory();
        Session ses = sf.openSession();
        ses.save(pInfo);
        ses.beginTransaction().commit();
        ses.evict(pInfo);

        // ses = sf.openSession();
        //                ses.save(pInfo);
        //                ses.beginTransaction().commit();
        pInfo = (StudentPersonalInfo) ses.get(StudentPersonalInfo.class, "13_CS_19");
        System.out.println(pInfo.getRollNum());
        System.out.println(pInfo.getName());

        //                ses.evict(m);
        //                ses.close(); 

        m = (Master) ses.get(Master.class, "cs");
        System.out.println(m.getDepart());
        System.out.println(m.getMasterKey());
        //                ses = sf.openSession();
        //                ses.save(db);
        //                ses.beginTransaction().commit();
        //                ses.evict(db);
        //                ses.close();
        // ses = sf.openSession();
        // m = (Student)ses.get(Student.class, 1);
        // System.out.println("Name="+m.getName());
        //                System.out.println("Id="+m.getId());

        ses.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.berlios.marmota.core.server.userManagment.UserManagment.java

License:Open Source License

/** 
 * Get all users// ww  w .j  a  v  a 2  s .  c  om
 * @see de.berlios.marmota.core.common.userManagment.UserRemoteInterface#getUsers()
 */
@SuppressWarnings("unchecked")
public List<User> getUsers() throws RemoteException {
    ArrayList<User> listForClient = new ArrayList<User>();
    Session session = Marmota.SESSION_FACTORY.openSession();
    List<User> userList = null;
    try {
        Query query = session.createQuery("select u from User u");
        userList = query.list();
        for (int i = 0; i < userList.size(); i++) {
            User u = userList.get(i);
            session.evict(u);
            listForClient.add(u);
        }
        session.close();
    } catch (Exception e) {
        Marmota.getLogger().error("Failed to get Users from DB: " + e.getMessage());
        if (session.isOpen()) {
            session.close();
        }
        return null;
    }
    return listForClient;
}

From source file:de.iew.framework.persistence.hibernate.HbmWebResourceDaoImpl.java

License:Apache License

/**
 * {@inheritDoc}/* w w  w . j  a  va2  s.c o  m*/
 * <p>
 * Evicts the loaded {@link WebResource} models from the hibernate session. We want to cache the web resources
 * independent from hibernate in the service. All required associations will be also evicted from the hibernate
 * session. Don't fear the Hibernate Exceptions :-)
 * </p>
 */
public Collection<RequestMapEntry> fetchRequestMap() throws ModelInstantiationException {
    Session session = getCurrentSession();

    List<RequestMapEntry> requestMapEntries = new ArrayList<RequestMapEntry>();

    Collection<WebResource> webResources = findAllOrderedAscending();

    RequestMapEntry requestMapEntry;
    RequestMatcher requestMatcher;
    Collection<ConfigAttribute> configAttributes;
    for (WebResource webResource : webResources) {
        requestMatcher = createRequestMatcherFromWebResource(webResource);
        configAttributes = createConfigAttributeFromWebResource(webResource);

        session.evict(webResource);
        requestMapEntry = new RequestMapEntry(requestMatcher, webResource, configAttributes);
        requestMapEntries.add(requestMapEntry);
    }

    return requestMapEntries;
}

From source file:de.ingrid.portal.interfaces.impl.DBAnniversaryInterfaceImpl.java

License:EUPL

/**
 * @see de.ingrid.portal.interfaces.SimilarTermsInterface#getAnniversary(java.sql.Date)
 *///ww  w .  j  a v  a 2  s .c om
public IngridHitDetail[] getAnniversaries(Date d, String lang) {

    Session session = HibernateUtil.currentSession();
    Transaction tx = null;
    try {
        Calendar queryDateFrom = Calendar.getInstance();
        queryDateFrom.set(Calendar.HOUR_OF_DAY, 0);
        queryDateFrom.set(Calendar.MINUTE, 0);
        queryDateFrom.set(Calendar.SECOND, 0);
        queryDateFrom.set(Calendar.MILLISECOND, 0);
        Calendar queryDateTo = Calendar.getInstance();
        queryDateTo.set(Calendar.HOUR_OF_DAY, 23);
        queryDateTo.set(Calendar.MINUTE, 59);
        queryDateTo.set(Calendar.SECOND, 59);
        queryDateTo.set(Calendar.MILLISECOND, 0);

        Calendar fromCal = Calendar.getInstance();
        Calendar toCal = Calendar.getInstance();

        fromCal.setTime(d);

        tx = session.beginTransaction();
        List anniversaryList = session.createCriteria(IngridAnniversary.class)
                .add(Restrictions.eq("dateFromDay", new Integer(fromCal.get(Calendar.DAY_OF_MONTH))))
                .add(Restrictions.eq("dateFromMonth", new Integer(fromCal.get(Calendar.MONTH) + 1)))
                .add(Restrictions.eq("language", lang)).list();
        tx.commit();

        if (anniversaryList.isEmpty()) {
            // fall back: get any event of this month
            fromCal.setTime(d);
            toCal.setTime(d);

            tx = session.beginTransaction();
            anniversaryList = session.createCriteria(IngridAnniversary.class)
                    .add(Restrictions.between("dateFromMonth", new Integer(fromCal.get(Calendar.MONTH) + 1),
                            new Integer(toCal.get(Calendar.MONTH) + 1)))
                    .add(Restrictions.sqlRestriction("length({alias}.date_from) > 4"))
                    .add(Restrictions.eq("language", lang)).list();
            tx.commit();

            if (anniversaryList.isEmpty()) {
                // fall back: get any event that has been fetched for today
                fromCal.setTime(d);

                tx = session.beginTransaction();
                anniversaryList = session.createCriteria(IngridAnniversary.class)
                        .add(Restrictions.eq("language", lang)).list();
                tx.commit();
            }
        }

        IngridHitDetail[] rslt = new IngridHitDetail[anniversaryList.size()];
        for (int i = 0; i < rslt.length; i++) {
            IngridAnniversary anni = (IngridAnniversary) anniversaryList.get(i);
            rslt[i] = new DetailedTopic();
            rslt[i].put("topicId", anni.getTopicId());
            rslt[i].put("topicName", anni.getTopicName());
            rslt[i].put("from", anni.getDateFrom());
            rslt[i].put("until", anni.getDateTo());
            rslt[i].put("until", anni.getDateTo());
            session.evict(anni);
        }

        return rslt;

    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        if (log.isErrorEnabled()) {
            log.error("Exception while querying sns for anniversary.", e);
        }
        return new DetailedTopic[0];
    } finally {
        HibernateUtil.closeSession();
    }
}