List of usage examples for org.hibernate Session saveOrUpdate
void saveOrUpdate(Object object);
From source file:com.javaweb.service.VeService.java
public boolean InsertVe(Ve ve) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx = null;/*from w w w . java 2 s . c om*/ try { tx = session.getTransaction(); tx.begin(); session.saveOrUpdate(ve); tx.commit(); return true; } catch (Exception e) { if (tx != null) { tx.rollback(); } System.out.println(e.toString()); } finally { session.close(); } return false; }
From source file:com.jdon.persistence.hibernate.HibernateTemplate.java
License:Apache License
public void saveOrUpdate(final Object entity) throws Exception { doHibernate(new HibernateCallback() { public Object execute(Session session) throws HibernateException { session.saveOrUpdate(entity); return null; }//from w w w. j a v a 2s. c om }); }
From source file:com.jdon.persistence.hibernate.HibernateTemplate.java
License:Apache License
public void saveOrUpdateAll(final Collection entities) throws Exception { doHibernate(new HibernateCallback() { public Object execute(Session session) throws HibernateException { for (Iterator it = entities.iterator(); it.hasNext();) { session.saveOrUpdate(it.next()); }//from w w w. j a va 2s.co m return null; } }); }
From source file:com.jonschang.investing.stocks.service.StockExchangeService.java
License:LGPL
private void primeExchanges() { exchangesPrimed = true;/* w ww . j a va 2 s . c o m*/ for (Map.Entry<String, StockExchange> se : exchanges.entrySet()) { StockExchange exchange = se.getValue(); Session session = Investing.instance().getSessionFactory().getCurrentSession(); session.beginTransaction(); StockExchange sel = (StockExchange) session.createQuery( "select se from StockExchange se left join fetch se.symbols where se.stockExchangeId=:id") .setInteger("id", exchange.getStockExchangeId()).uniqueResult(); session.getTransaction().commit(); if (sel == null) { if (exchange.getSymbols() != null) for (StockExchangeSymbol symbol : exchange.getSymbols()) symbol.setParent(exchange); session = Investing.instance().getSessionFactory().getCurrentSession(); session.beginTransaction(); session.save(exchange); session.getTransaction().commit(); } else { boolean updated = false; for (StockExchangeSymbol xmlSym : exchange.getSymbols()) { boolean found = false; for (StockExchangeSymbol sym : sel.getSymbols()) { if (sym.getSymbol().compareTo(xmlSym.getSymbol()) == 0) { found = true; break; } } if (!found) { updated = true; sel.getSymbols().add(xmlSym); xmlSym.setParent(sel); } } if (updated) { session = Investing.instance().getSessionFactory().getCurrentSession(); session.beginTransaction(); session.saveOrUpdate(sel); session.getTransaction().commit(); } } } }
From source file:com.jonschang.investing.stocks.service.YahooHistoricalStockQuoteService.java
License:LGPL
/** * when the quotes get pulled from yahoo, dates that i expect to have * that don't return anything get inserted as quotes with a closing * price of -404.0// w ww . j ava 2 s . co m * @param qr * @throws ServiceException * @throws HibernateException */ protected void pullNeededQuotesFromWebService(QuoteRequest qr) throws ServiceException { // iterate over the stocks we need to pull quotes for from yahoo // and pull them from yahoo and persist them BusinessCalendar tempCal = newClosestAfterStart(qr); tempCal.normalizeToMinute(); for (Map.Entry<Stock, List<DateRange>> entry : qr.needToPull.entrySet()) { Stock stock = entry.getKey(); List<DateRange> missingDateRanges = entry.getValue(); if (stock.getStockQuotes() == null) stock.setStockQuotes(new ArrayList<StockQuote>()); m_logger.trace("PROCESSING missing date ranges for " + stock.getSymbol() + " between " + qr.busCalLow.getTime().toString() + " and " + qr.busCalHigh.getTime().toString()); for (DateRange dateRange : missingDateRanges) { m_logger.trace("about to pull missing date range from Yahoo! between " + stock.getSymbol() + " between " + dateRange.getStart() + " and " + dateRange.getEnd()); try { try { pullQuotesBetween(stock, dateRange.getStart(), dateRange.getEnd(), qr.interval, tempCal); } catch (java.io.FileNotFoundException fnfe) { // there be no quotes in all of yahoo! for this period, arrrr. m_logger.warn("no quotes returned from \"Yahoo!\" for " + stock.getSymbol() + " between " + dateRange.getStart().toString() + " and " + dateRange.getEnd().toString() + "."); // there is no result, so i should just go to the next date range continue; } Map<Date, StockQuote> dateToQuoteMap = new HashMap<Date, StockQuote>(); for (StockQuote sq : stock.getStockQuotes()) dateToQuoteMap.put(sq.getDate(), sq); pullKeyEventData(m_splitUrl, stock, newClosestAfterStart(qr), qr.interval, dateRange, dateToQuoteMap); pullKeyEventData(m_dividendUrl, stock, newClosestAfterStart(qr), qr.interval, dateRange, dateToQuoteMap); // http://chartapi.finance.yahoo.com/instrument/1.0/mdr/chartdata;type=dividend;ys=1980;yz=100/xml/ // http://finance.yahoo.com/webservice/v1/keyevents/msft/it;range=20070101,20080101 } catch (DocumentException de) { throw new ServiceException("A DocumentException occurred trying to pull event data from Yahoo!", de); } catch (IOException ioe) { throw new ServiceException("An IOException occurred trying to pull quotes from Yahoo!", ioe); } catch (Exception e) { throw new ServiceException( "An unhandled exception occurred trying to pull quote information from Yahoo!", e); } m_logger.trace("verifying that quotes are ordered by date"); StockQuote lastQ = null; for (StockQuote sq : stock.getStockQuotes()) { m_logger.trace("verifying quote sort: quote date is " + sq.getDate() + " and closing is " + sq.getPriceClose()); if (lastQ != null && !lastQ.getDate().before(sq.getDate())) m_logger.error("damn, i've sorted this twice and it's still out of order?"); lastQ = sq; } Session session = Investing.instance().getSessionFactory().getCurrentSession(); List<StockQuote> cachedQuotes = stock.getStockQuotes(); session.beginTransaction(); session.saveOrUpdate(stock); session.getTransaction().commit(); stock.setStockQuotes(cachedQuotes); // so we don't end up with one of those damn persistence bags } // iteration over missingDateRanges per each stock } // iteration over stocks not pulled }
From source file:com.jonschang.investing.stocks.service.YahooStockService.java
License:LGPL
protected Stock pullStockFromWebService(Stock stock) throws ServiceException { String urlStr = STOCK_EXCHANGE_URL.replace("{SYMBOL}", stock.getSymbol()); try {//from w w w . java 2 s . co m String content = null; if (stock.getSymbol().startsWith("^")) { content = "\"" + stock.getSymbol() + "\",\"INDEX\""; } else { URL url = new URL(urlStr); Logger.getLogger(this.getClass()) .info("Attempting to pulling stock information from Yahoo! at url " + url); content = FileUtils.readInputStream((InputStream) url.getContent()); if (content == null) { throw new NotFoundException("no stock information found in \"" + content + "\" at url " + url); } } if (content != null) { String[] parts = content.trim().split("\",\""); String companyName = parts[0].replace("\"", ""); String exchangeSymbol = parts[1].replace("\"", ""); stock.setCompanyName(companyName); // if we couldn't find the stock under the symbol if (stock.getStockExchange() != null && stock.getStockExchange().getSymbol() != null && stock.getStockExchange().getSymbol().compareTo(exchangeSymbol) != 0) throw new NotFoundException("the stock symbol requested \"" + stock.getSymbol() + "\" was found under the exchange \"" + exchangeSymbol + "\", not \"" + stock.getStockExchange().getSymbol() + "\""); // if the exchange does not have a pkid, then attempt to use the StockExchangeService to discover it StockExchange pulledExchange = (StockExchange) Investing.instance().getExchangeServiceFactory() .get(StockExchange.class).getExchange(exchangeSymbol); if (pulledExchange == null) throw new NotFoundException("the stock with symbol \"" + stock.getSymbol() + "\" was found, but the exchange \"" + exchangeSymbol + "\" was not. do you need to add the exchange to StockExchangeService in exchange-service.xml?"); else { //pulledExchange.getStocks().add(stock); stock.setStockExchange(pulledExchange); } // now we need to store the stock to the databased Session session = Investing.instance().getSessionFactory().getCurrentSession(); session.beginTransaction(); session.saveOrUpdate(stock); session.refresh(stock); session.getTransaction().commit(); } Logger.getLogger(YahooStockService.class).info(content); pullSectorAndIndustryFromYahoo(stock); return stock; } catch (MalformedURLException mue) { throw new ServiceException("Parser threw a MalformedURLException looking for symbol " + stock.getSymbol() + " from Yahoo! at url " + urlStr, mue); } catch (IOException pe) { throw new ServiceException("Parser threw a IOException looking for symbol " + stock.getSymbol() + " from Yahoo! at url " + urlStr, pe); } }
From source file:com.jonschang.investing.stocks.service.YahooStockService.java
License:LGPL
private void pullSectorAndIndustryFromYahoo(Stock stock) throws ServiceException { try {//w w w.j av a 2 s . co m boolean saveOrUpdate = false; if (stock.getSymbol().charAt(0) != '^') { String url = "http://finance.yahoo.com/q/pr?s=" + stock.getSymbol(); Logger.getLogger(this.getClass()).info("Pulling sector and industry classification for stock " + stock.getSymbol() + " from Yahoo! at url " + url); Parser parser = new Parser(url); NodeList sectorNodes = parser.parse(new ExtractTwoColumnRowValue("Sector:")); parser.reset(); NodeList industryNodes = parser.parse(new ExtractTwoColumnRowValue("Industry:")); if (sectorNodes.size() > 0 && industryNodes.size() > 0) { stock.setIndustry(industryNodes.elementAt(0) instanceof LinkTag ? industryNodes.elementAt(0).getChildren().elementAt(0).toHtml().trim() : industryNodes.toHtml().trim()); stock.setSector(sectorNodes.elementAt(0) instanceof LinkTag ? sectorNodes.elementAt(0).getChildren().elementAt(0).toHtml().trim() : sectorNodes.toHtml().trim()); saveOrUpdate = true; } else throw new NotFoundException( "Could not find sector and industry information for " + stock.getSymbol()); } else { Logger.getLogger(this.getClass()).info( "Skipping attempt to obtain sector and industry for Index quotable " + stock.getSymbol()); stock.setSector("index"); stock.setIndustry("index"); saveOrUpdate = true; } if (saveOrUpdate) { // now we need to store the stock to the databased Session session = Investing.instance().getSessionFactory().getCurrentSession(); session.beginTransaction(); session.saveOrUpdate(stock); session.getTransaction().commit(); } } catch (ParserException pe) { throw new ServiceException("Parser could not determine sector OR industry for symbol " + stock.getSymbol() + " profile pulled from Yahoo!"); } }
From source file:com.js.jd.models.dao.hql.HQLGenericDAO.java
@Override public void saveOrUpdate(T entity) throws BussinessException { Session session = sessionFactory.getCurrentSession(); try {/* ww w . jav a2 s.c o m*/ session.beginTransaction(); session.saveOrUpdate(entity); session.getTransaction().commit(); } catch (javax.validation.ConstraintViolationException | org.hibernate.exception.ConstraintViolationException cve) { try { if (session.getTransaction().isActive()) { session.getTransaction().rollback(); } } catch (Exception exc) { LOGGER.log(Level.WARNING, "Fall al hacer un rollback", exc); } throw new BussinessException(cve); } catch (RuntimeException ex) { try { if (session.getTransaction().isActive()) { session.getTransaction().rollback(); } } catch (Exception exc) { LOGGER.log(Level.WARNING, "Fall al hacer un rollback", exc); } throw ex; } catch (Exception ex) { try { if (session.getTransaction().isActive()) { session.getTransaction().rollback(); } } catch (Exception exc) { LOGGER.log(Level.WARNING, "Fall al hacer un rollback", exc); } throw new RuntimeException(ex); } }
From source file:com.knowbout.epg.entities.Credit.java
License:Apache License
public void insert() { Session session = HibernateUtil.currentSession(); session.saveOrUpdate(this); }
From source file:com.krawler.esp.handlers.CompanyHandler.java
License:Open Source License
public static TaxList setNewTax(Session session, HttpServletRequest request, JSONObject jobj, Tax tax) throws ServiceException, HibernateException, JSONException { TaxList taxlist = null;/*from w w w . j av a2 s . com*/ try { List list = null; ArrayList params = new ArrayList(); Date appDate = AuthHandler.getDateFormatter(request).parse(jobj.getString("applydate")); Company company = (Company) session.get(Company.class, AuthHandler.getCompanyid(request)); String query = "from TaxList where applyDate=? and tax.ID=? and company.companyID=?"; params.add(appDate); params.add(tax.getID()); params.add(company.getCompanyID()); list = HibernateUtil.executeQuery(session, query, params.toArray()); if (list != null && !list.isEmpty()) { taxlist = (TaxList) list.get(0); } else taxlist = new TaxList(); taxlist.setApplyDate(appDate); taxlist.setTax(tax); taxlist.setCompany(company); taxlist.setPercent(Double.parseDouble(jobj.getString("percent"))); session.saveOrUpdate(taxlist); } catch (SessionExpiredException ex) { throw ServiceException.FAILURE("CompanyHandler.setNewTax", ex); } catch (ParseException ex) { throw ServiceException.FAILURE("CompanyHandler.setNewTax", ex); } return taxlist; }