Java Code Examples for org.hibernate.Session.isOpen()

The following are Jave code examples for showing how to use isOpen() of the org.hibernate.Session class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: sjk   File: AppHistory4IndexDaoImpl.java   Source Code and License Vote up 12 votes
/**
 * 更新 状态到数据库,仅针对 appStatus 为 1(add) 2(update) 更新索引 ,
 */
@Override
public int updateAppHistory4indeToIndexed(List<Integer> appIds) {
    String hql = "update AppHistory4Index set indexStatus=1,lastIndexTime=:lastIndexTime where (appStatus=1 or appStatus=2) and appId in (:appIds)";

    Session session = null;
    try {
        session = this.sessions.openSession();
        Query query = session.createQuery(hql);
        query.setParameterList("appIds", appIds);
        query.setTimestamp("lastIndexTime", new Date());

        return query.executeUpdate();
    } catch (Exception e) {
        logger.error("error:", e);
        return 0;
    } finally {
        if (session != null && session.isOpen()) {
            session.flush();
            session.clear();
            session.close();
        }
    }

}
 
Example 2
Project: sjk   File: AppHistory4IndexDaoImpl.java   Source Code and License Vote up 6 votes
@Override
public List<AppHistory4Index> getApps(int currentPage, int pageSize) {
    String hql = "from AppHistory4Index appIdx where appIdx.indexStatus<>1";

    Session session = null;
    try {
        session = this.sessions.openSession();

        Query q = session.createQuery(hql);
        q.setFirstResult(HibernateHelper.firstResult(currentPage, pageSize));
        q.setMaxResults(pageSize);
        return HibernateHelper.list(q);
    } catch (Exception e) {
        logger.error("error:", e);
        return null;
    } finally {
        if (session != null && session.isOpen()) {
            session.clear();
            session.close();
        }
    }
}
 
Example 3
Project: sjk   File: AppHistory4IndexDaoImpl.java   Source Code and License Vote up 6 votes
@Override
public List<AppHistory4Index> getApps() {
    String hql = "from AppHistory4Index appIdx where appIdx.indexStatus<>1";

    Session session = null;
    try {
        session = this.sessions.openSession();
        return HibernateHelper.list(session.createQuery(hql));
    } catch (Exception e) {
        logger.error("error:", e);
        return null;
    } finally {
        if (session != null && session.isOpen()) {
            session.clear();
            session.close();
        }
    }
}
 
Example 4
Project: sjk   File: AppHistory4IndexDaoImpl.java   Source Code and License Vote up 6 votes
@Override
public int delAppHistory4index(List<Integer> appIds) {

    // String hql =
    // "delete  AppHistory4Index  where appStatus=3 and indexStatus=-1 and appId in (:appIds)";
    // 删除前一天生成索引的数据,避免数据过多
    String hql = "delete  AppHistory4Index  where (indexStatus=-1 and appId in (:appIds) ) or lastIndexTime<:lastIndexTime";
    Session session = null;
    try {
        session = this.sessions.openSession();
        Query query = session.createQuery(hql);
        query.setParameterList("appIds", appIds);
        query.setTimestamp("lastIndexTime", DateUtils.addDays(new Date(), -1));// 删除前一天索引后的数据

        return query.executeUpdate();
    } catch (Exception e) {
        logger.error("error:", e);
        return 0;
    } finally {
        if (session != null && session.isOpen()) {
            session.flush();
            session.clear();
            session.close();
        }
    }

}
 
Example 5
Project: sjk   File: AppHistory4IndexDaoImpl.java   Source Code and License Vote up 6 votes
/**
 * 设置appStatus 状态 为可删除 状态 3,索引状态 indexStatus为 -1
 */
@Override
public int updateAppStatus2Del(List<Integer> ids) {
    Session session = null;

    try {
        session = this.sessions.openSession();

        String hql = "update AppHistory4Index set appStatus=3,indexStatus=-1,lastOpTime=:lastOpTime where appId in (:appIds)";
        Query query = session.createQuery(hql);
        query.setParameterList("appIds", ids);
        query.setTimestamp("lastOpTime", new Date());

        return query.executeUpdate();

    } catch (Exception e) {
        logger.error("error:", e);
        return 0;
    } finally {
        if (session != null && session.isOpen()) {
            session.flush();
            session.clear();
            session.close();
        }
    }

}
 
Example 6
Project: sjk   File: AppHistory4IndexDaoImpl.java   Source Code and License Vote up 6 votes
@Override
public int updateAppStatus2Del(Integer id) {
    Session session = null;

    try {
        session = this.sessions.openSession();
        //
        String hql = "update AppHistory4Index set appStatus=3,indexStatus=-1,lastOpTime=:lastOpTime where appId =:appId";
        Query query = session.createQuery(hql);
        query.setInteger("appId", id);
        query.setTimestamp("lastOpTime", new Date());

        return query.executeUpdate();

    } catch (Exception e) {
        logger.error("error:", e);
        return 0;
    } finally {
        if (session != null && session.isOpen()) {
            session.flush();
            session.clear();
            session.close();
        }
    }
}
 
Example 7
Project: TrabalhoCrisParte2   File: DAOHibernateUtil.java   Source Code and License Vote up 5 votes
/**
 *
 * @return 
 */
public static Session getSession(){
    Session session = (Session) DAOHibernateUtil.session.get();
    
    if(session == null || !session.isOpen()){
        session = sessionFactory.openSession();
        DAOHibernateUtil.session.set(session);
    }
    
    return session;
}
 
Example 8
Project: WeiXing_xmu-2016-MrCode   File: HibernateSessionFactory.java   Source Code and License Vote up 5 votes
/**
   * Returns the ThreadLocal Session instance.  Lazy initialize
   * the <code>SessionFactory</code> if needed.
   *
   *  @return Session
   *  @throws HibernateException
   */
  public static Session getSession() throws HibernateException {
      Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {
	if (sessionFactory == null) {
		rebuildSessionFactory();
	}
	session = (sessionFactory != null) ? sessionFactory.openSession()
			: null;
	threadLocal.set(session);
}

      return session;
  }
 
Example 9
Project: lams   File: SessionHolder.java   Source Code and License Vote up 5 votes
public Session getValidatedSession(Object key) {
	Session session = this.sessionMap.get(key);
	// Check for dangling Session that's around but already closed.
	// Effectively an assertion: that should never happen in practice.
	// We'll seamlessly remove the Session here, to not let it cause
	// any side effects.
	if (session != null && !session.isOpen()) {
		this.sessionMap.remove(key);
		session = null;
	}
	return session;
}
 
Example 10
Project: lams   File: HibernateSessionManager.java   Source Code and License Vote up 5 votes
public static void closeSession() {
	Session session = HibernateSessionManager.getSessionFactory().getCurrentSession();
	if (session.isOpen()) {
//	    log.debug("Closing session transaction "+session.getTransaction());
	    session.close();
	}
    }
 
Example 11
Project: ReadMe   File: HibernateSessionFactory.java   Source Code and License Vote up 5 votes
/**
 * Returns the ThreadLocal Session instance.  Lazy initialize
 * the <code>SessionFactory</code> if needed.
 *
 *  @return Session
 *  @throws HibernateException
 */
public static Session getSession() throws HibernateException {
    Session session = (Session) threadLocal.get();

    if (session == null || !session.isOpen()) {
        if (sessionFactory == null) {
            rebuildSessionFactory();
        }
        session = (sessionFactory != null) ? sessionFactory.openSession()
                : null;
        threadLocal.set(session);
    }

    return session;
}
 
Example 12
Project: hibernateMaster   File: HibernateUtil.java   Source Code and License Vote up 5 votes
public static void closeSession() {
	Session session = null;
	if (Config.isSignalDatabase) {
		session = threadLocal.get();
	}else {
		session = getSessionMap().get(getCurrentDatabase());
	}
	if(session != null && session.isOpen()){
		session.close();
	}
	threadLocal.remove();
	closeSession.remove();
}
 
Example 13
Project: hibernateMaster   File: HibernateUtil.java   Source Code and License Vote up 5 votes
public static void release(){
	closeSession();
	for (Entry<String, Session> e:getSessionMap().entrySet()) {
		Session value = e.getValue();
		if (value!= null&&value.isOpen()) {
			value.close();
		}
	}
	currentDatabase.remove();
	sessionStory.remove();
}
 
Example 14
Project: bdf2   File: ContextHolder.java   Source Code and License Vote up 5 votes
public static void clean(){
	if (null!=hibernateSessionMapThreadLocal.get()){
		for(Session session:hibernateSessionMapThreadLocal.get().values()){
			if(session.isOpen()){
				session.flush();
				session.close();				
			}
		}
	}
	hibernateSessionMapThreadLocal.remove();
	responseThreadLocal.remove();
	requestThreadLocal.remove();
	currentDataSourceNameThreadLocal.remove();
}
 
Example 15
Project: bdf2   File: JdbcTransactionManager.java   Source Code and License Vote up 5 votes
private void clean(){
	Map<String,Session> sessionMap=ContextHolder.getHibernateSessionMap();
	if(sessionMap==null){
		return;
	}
	for(Session session:sessionMap.values()){
		if(session!=null && session.isOpen()){
			session.flush();
			session.close();
			session=null;
		}
	}
	sessionMap.clear();		
}
 
Example 16
Project: bdf2   File: ContextHolder.java   Source Code and License Vote up 5 votes
public static void clean(){
	for(Session session:hibernateSessionMapThreadLocal.get().values()){
		if(session.isOpen()){
			session.flush();
			session.close();				
		}
	}
	hibernateSessionMapThreadLocal.remove();
	responseThreadLocal.remove();
	requestThreadLocal.remove();
	currentDataSourceNameThreadLocal.remove();
}
 
Example 17
Project: bdf2   File: JdbcTransactionManager.java   Source Code and License Vote up 5 votes
private void clean(){
	Map<String,Session> sessionMap=ContextHolder.getHibernateSessionMap();
	if(sessionMap==null){
		return;
	}
	for(Session session:sessionMap.values()){
		if(session!=null && session.isOpen()){
			session.flush();
			session.close();
			session=null;
		}
	}
	sessionMap.clear();		
}
 
Example 18
Project: sjk   File: ApiImporterMarketServiceImpl.java   Source Code and License Vote up 4 votes
@Override
public void importIncrement() {
    logger.info("{}. ImportIncrement begins...", this.getMarketName());
    Session session = null;
    Transaction tx = null;
    boolean successed = false;
    Date now = new Date();
    do {
        session = sessions.openSession();
        session.setDefaultReadOnly(false);
        try {
            Market market = null;
            try {
                market = getMarket(session);
            } finally {
                session.close();
            }
            int currentPage = 0, totalPage = 0;
            oneIncrement: do {
                PaginationMarketApp increment = getMarketAppForIncrement(market);
                if (increment != null) {
                    currentPage = increment.getCurrentPage();
                    totalPage = increment.getTotalPages();
                    List<MarketApp> marketApps = increment.getData();
                    List<MarketApp> offMarketApps = new ArrayList<MarketApp>();
                    if (marketApps != null && !marketApps.isEmpty()) {
                        // open again
                        if (!session.isOpen()) {
                            session = sessions.openSession();
                        }
                        tx = session.beginTransaction();
                        savePaginationMarketApp(session, market, marketApps, offMarketApps);
                        market.setIncrementLastReqCurrentPage(currentPage);
                        market.setIncrementTotalPages(totalPage);
                        session.merge(market);
                        tx.commit();
                        tx = null;
                        session.close();
                        deleteMarketAppsTransaction(offMarketApps);
                        logger.info(
                                "{}. Increment totalPage: {}\t currentPage: {}\t size: {}\t offMarketApps size: {}",
                                this.getMarketName(), totalPage, currentPage, marketApps.size(),
                                offMarketApps.size());
                        marketApps.clear();
                        offMarketApps.clear();
                    }
                    if (currentPage >= totalPage) {
                        successed = true;
                    }
                } else {
                    successed = false;
                    break oneIncrement;
                }
            } while (totalPage > 0 && currentPage < totalPage);
            if (successed) {
                resetMarketForIncrement(now);
            } else {
                sleepForTry();
            }
        } catch (Exception e) {
            successed = false;
            if (tx != null) {
                tx.rollback();
            }
            logger.error("Exception", e);
            sleepForTry();
        } finally {
            if (session.isOpen()) {
                session.close();
            }
        }
    } while (!successed);
    logger.info("{}. ImportIncrement done!", this.getMarketName());
}
 
Example 19
Project: sjk   File: ApiImporterMarketServiceImpl.java   Source Code and License Vote up 4 votes
private PaginationMarketApp savePaginationForFull() throws Exception {
    // saveOrUpdate to table MarketApp
    PaginationMarketApp marketPagination = null;
    Session session = sessions.openSession();
    session.setDefaultReadOnly(false);
    Transaction tx = null;
    try {
        Market market = getMarket(session);
        marketPagination = getMarketAppForFull(market);
        if (marketPagination != null && marketPagination.getTotalPages() >= marketPagination.getCurrentPage()) {
            List<MarketApp> marketApps = marketPagination.getData();
            List<MarketApp> offMarketApps = new ArrayList<MarketApp>();
            if (marketApps != null && !marketApps.isEmpty()) {
                Object[] infos = new Object[] { market.getMarketName(), marketPagination.getTotalPages(),
                        marketPagination.getCurrentPage(), marketApps.size() };
                accessMarketDao.getMarketlogger().info(
                        "Begin to import {} on one page. totalPages: {} currentPage : {} , size: {}", infos);
                tx = session.beginTransaction();
                savePaginationMarketApp(session, market, marketApps, offMarketApps);
                market.setFullLastReqCurrentPage(marketPagination.getCurrentPage());
                market.setFullTotalPages(marketPagination.getTotalPages());
                market.setFullLastTime(new Date());
                session.merge(market);
                tx.commit();
                tx = null;
                session.clear();
                session.close();
                deleteMarketAppsTransaction(offMarketApps);
                marketApps.clear();
                offMarketApps.clear();
            }
        }
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        logger.error("Exception", e);
        throw e;
    } finally {
        if (session.isOpen()) {
            session.close();
        }
    }
    return marketPagination;
}
 
Example 20
Project: sjk   File: AppDaoImpl.java   Source Code and License Vote up 4 votes
@Override
public List<App> getApps(List<Integer> appIds) {
    String hql = "select id,name,catalog,subCatalog,keywords,description,downloadRank,adPopupTypes,signatureSha1,officialSigSha1,marketName from App app where app.hidden=0 and app.id in(:appIds)";

    Session session = null;
    try {
        session = this.sessions.openSession();
        Query query = session.createQuery(hql);
        query.setParameterList("appIds", appIds);
        List<Object[]> list = HibernateHelper.list(query);

        List<App> apps = null;
        if (list != null && !list.isEmpty()) {
            apps = new ArrayList<App>(list.size());
            for (Object[] obj : list) {
                App a = new App();
                String tmp = null;
                a.setId((Integer) obj[0]);
                a.setName(((String) obj[1]).toLowerCase().trim());
                a.setCatalog((Short) obj[2]);
                a.setSubCatalog((Integer) obj[3]);
                if ((tmp = (String) obj[4]) == null) {
                    a.setKeywords("");
                } else {
                    a.setKeywords(tmp.toLowerCase().trim());
                }
                if ((tmp = (String) obj[4]) == null) {
                    a.setDescription("");
                } else {
                    a.setDescription(tmp.toLowerCase().trim());
                }
                a.setDownloadRank((Integer) obj[6]);
                /* safe scan */
                a.setAdPopupTypes((String) obj[7]);
                a.setSignatureSha1((String) obj[8]);
                a.setOfficialSigSha1((String) obj[9]);
                /* safe scan */
                a.setMarketName((String) obj[10]);
                apps.add(a);
            }
            list.clear();
        }
        return apps;
    } catch (Exception e) {
        logger.error("error:", e);
        return null;
    } finally {
        if (session != null && session.isOpen()) {
            session.clear();
            session.close();
        }
    }
}