List of usage examples for org.hibernate Session createSQLQuery
@Override NativeQuery createSQLQuery(String queryString);
From source file:ch.algotrader.service.mysql.MySqlTransactionPersistenceServiceImpl.java
License:Open Source License
/** * {@inheritDoc}//from www . j ava 2 s . co m */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public void ensurePositionAndCashBalance(final Transaction transaction) { Validate.notNull(transaction, "Transaction is null"); transaction.initializeSecurity(HibernateInitializer.INSTANCE); Strategy strategy = transaction.getStrategy(); Security security = transaction.getSecurity(); Set<Currency> currencySet = new HashSet<>(); Collection<CurrencyAmountVO> attributions = transaction.getAttributions(); for (CurrencyAmountVO attribution : attributions) { currencySet.add(attribution.getCurrency()); } Session currentSession = this.sessionFactory.getCurrentSession(); if (security != null) { Serializable id = HibernateUtil.getNextId(this.sessionFactory, PositionImpl.class); SQLQuery sqlQuery = currentSession.createSQLQuery("INSERT IGNORE INTO position " + " (id, quantity, cost, realized_p_l, persistent, security_fk, strategy_fk, version) " + " VALUES (:position_id, 0, 0, 0, 0, :security_id, :strategy_id, 1)"); sqlQuery.setParameter("position_id", id); sqlQuery.setParameter("security_id", security.getId()); sqlQuery.setParameter("strategy_id", strategy.getId()); sqlQuery.executeUpdate(); } if (!currencySet.isEmpty()) { SQLQuery sqlQuery = currentSession.createSQLQuery("INSERT IGNORE INTO cash_balance " + "(currency, amount, strategy_fk, version) VALUES (:currency, 0, :strategy_id, 1)"); for (Currency currency : currencySet) { sqlQuery.setParameter("currency", currency.name()); sqlQuery.setParameter("strategy_id", strategy.getId()); sqlQuery.executeUpdate(); } } }
From source file:ch.bbw.cms.database.HibernateDatabase.java
License:GNU General Public License
private boolean execute(String mysqlQuery) { analyze.count("execute"); if (Const.LOG_DEBUG) { logger.debug("MySQL Query: " + mysqlQuery); }//www . j av a 2 s . c o m boolean worked = true; Session session = initSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.createSQLQuery(mysqlQuery).executeUpdate(); tx.commit(); } catch (HibernateException e) { if (tx != null) tx.rollback(); worked = false; e.printStackTrace(); } finally { session.close(); } return worked; }
From source file:ch.systemsx.cisd.openbis.generic.server.dataaccess.db.AbstractDAO.java
License:Apache License
/** * Executes given <var>sql</var>. * <p>//from w ww . j a va 2 s. c om * Should be an <code>INSERT</code> or <code>UPDATE</code> statement. * </p> */ protected final void executeUpdate(final String sql, final Serializable... parameters) { getHibernateTemplate().execute(new HibernateCallback() { // // HibernateCallback // public final Object doInHibernate(final Session session) throws HibernateException, SQLException { final SQLQuery sqlQuery = session.createSQLQuery(sql); for (int i = 0; i < parameters.length; i++) { Serializable parameter = parameters[i]; if (parameter instanceof Long) { sqlQuery.setLong(i, (Long) parameter); } else if (parameter instanceof Integer) { sqlQuery.setInteger(i, (Integer) parameter); } else if (parameter instanceof Character) { sqlQuery.setCharacter(i, (Character) parameter); } else if (parameter instanceof Date) { sqlQuery.setDate(i, (Date) parameter); } else { sqlQuery.setSerializable(i, parameter); } } sqlQuery.executeUpdate(); return null; } }); }
From source file:ch.systemsx.cisd.openbis.generic.server.dataaccess.db.AbstractDAO.java
License:Apache License
/** * Natively performs given <var>sql</var> and returns an unique result by calling * {@link Query#uniqueResult()}.//from w ww . jav a 2 s. com */ @SuppressWarnings("unchecked") protected final <T> T getUniqueResult(final String sql, final Object... parameters) { return (T) getHibernateTemplate().execute(new HibernateCallback() { // // HibernateCallback // public final Object doInHibernate(final Session session) { return session.createSQLQuery(String.format(sql, parameters)).uniqueResult(); } }); }
From source file:ch.systemsx.cisd.openbis.generic.server.dataaccess.db.ExternalDataDAO.java
License:Apache License
@SuppressWarnings("unchecked") public Set<TechId> findParentIds(final Collection<TechId> dataSetIds) { // Native SQL query is used to be able to query on 'many-to-many association table - // - 'data_set_relationships' without join with 'data' table involved in this association. // Drawback of this solution is that instead of list of Long values we get list of // BigIntegers and so a transformation is needed. final String query = "select data_id_parent from data_set_relationships where data_id_child in (:ids)"; final List<? extends Number> results = (List<? extends Number>) getHibernateTemplate() .execute(new HibernateCallback() { // // HibernateCallback // public final Object doInHibernate(final Session session) { // we could remove this transformation if we choose to pass Long values final List<Long> longIds = transformTechIds2Longs(dataSetIds); return session.createSQLQuery(query).setParameterList("ids", longIds).list(); }// www .j a v a 2 s. c o m }); return transformNumbers2TechIds(results); }
From source file:ch.tatool.app.service.impl.UserAccountDAO.java
License:Open Source License
public void setAccountPassword(final UserAccountImpl account, final String password) { getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) { // find the username BasicDataSource dataSource = (BasicDataSource) account.getBeanFactory() .getBean("userAccountDataSource"); String username = dataSource.getUsername(); String newPassword = password != null ? password : ""; //String driver = dataSource.getDriverClassName(); // update the password using an alter user sql query (every db except mysql) try { StringBuilder sql = new StringBuilder(); sql.append("ALTER USER '").append(username).append("' SET PASSWORD '").append(newPassword) .append("'"); SQLQuery query = session.createSQLQuery(sql.toString()); query.executeUpdate();//from w w w . j ava 2 s .co m // update the current account object dataSource.setPassword(newPassword); account.setPassword(newPassword); account.setPasswordProtected(!newPassword.isEmpty()); } catch (HibernateException hb) { //TODO: Add something } return null; } }); }
From source file:ch.tatool.app.service.impl.UserAccountDAO.java
License:Open Source License
/** Set the scripttype used in the database to compressed. *///from w w w. j av a 2 s. c o m private void setScriptType(final UserAccountImpl account) { getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) { try { // SET FILES SCRIPT FORMAT {TEXT | COMPRESSED}; // http://hsqldb.org/doc/2.0/guide/deployment-chapt.html#deploymen_modes-sect // COMPRESSED leads to problems with Test, therefore we go with TEXT format String sql = "SET FILES SCRIPT FORMAT TEXT"; SQLQuery query = session.createSQLQuery(sql); query.executeUpdate(); } catch (HibernateException hb) { } return null; } }); }
From source file:ch.tatool.app.service.impl.UserAccountDAO.java
License:Open Source License
public void shutdown() { getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) { try { String sql = "SHUTDOWN"; SQLQuery query = session.createSQLQuery(sql); query.executeUpdate();//from w w w . j a va2 s . c o m } catch (HibernateException hb) { } return null; } }); }
From source file:club.jmint.mifty.example.ExaServiceImpl.java
License:Apache License
/** * @param {"hello":"Good morning!","name":"Darren"} *///from ww w .j a v a2s . c o m public String sayHello(String params, boolean isEncrypt) throws TException { //parse parameters and verify signature CrossLog.logger.debug("sayHello: " + params); JsonObject ip; try { ip = parseInputParams(params, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //validate parameters on business side String name, hello; try { name = getParamAsString(ip, "name"); hello = getParamAsString(ip, "hello"); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //do more checks here if you need. Session session = Dao.getSessionFactory().openSession(); session.beginTransaction(); session.createSQLQuery("insert into test.user (uid,name) values (3,'zhouguoxing'); ").executeUpdate(); SQLQuery sq = session.createSQLQuery("select * from test.user;"); System.out.println(sq.getFirstResult()); session.createSQLQuery("delete from test.user where uid=1; ").executeUpdate(); session.getTransaction().commit(); session.close(); //do your business logics System.out.println("name: " + name); System.out.println("hello: " + hello); CrossLog.logger.info("\nname: " + name + "\nsay: " + hello); String sentence = "Hi, " + name + " ," + hello; //do more things here. //build response parameters JsonObject op = new JsonObject(); op.addProperty("sentence", sentence); String output = null; try { output = buildOutputParams(op, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } CrossLog.logger.debug("sayHello: " + output); return output; }
From source file:cn.dao.MedicinePurchaseDao.java
public int getPageCount(Session session, String hql, Map properties) { StringBuffer countHql = new StringBuffer(); countHql.append("select count(1) from("); countHql.append(hql);/*from w ww . j a va 2 s .co m*/ countHql.append(") c"); Query query = session.createSQLQuery(countHql.toString()); if (properties != null) { query.setProperties(properties); } return Integer.parseInt(query.uniqueResult().toString()); }