Example usage for org.hibernate Session createSQLQuery

List of usage examples for org.hibernate Session createSQLQuery

Introduction

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

Prototype

@Override
    NativeQuery createSQLQuery(String queryString);

Source Link

Usage

From source file:com.all.client.model.LocalModelDao.java

License:Apache License

@SuppressWarnings("unchecked")
public Object deleteSyncEventEntities(Long timestamp) {
    final String sql = "delete from SyncEventEntity where timestamp = " + timestamp;
    return hibernateTemplate.execute(new HibernateCallback() {
        @Override/*from  w  w  w .  ja va 2  s .c o m*/
        public Object doInHibernate(Session session) throws SQLException {
            return session.createSQLQuery(sql).executeUpdate();
        }
    });
}

From source file:com.allinfinance.commquery.dao.CommQueryDAO.java

License:Open Source License

public void excute(final String sql) {
    getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            session.getTransaction().begin();
            Query query = session.createSQLQuery(sql);
            int executeColum = query.executeUpdate();
            session.getTransaction().commit();
            return executeColum;
        }//www.j av a  2  s. co m
    });
}

From source file:com.allinfinance.commquery.dao.CommQueryDAO.java

License:Open Source License

public int excuteWithoutTransaction(final String sql) {
    int i = (Integer) this.getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createSQLQuery(sql);
            int executeColum = query.executeUpdate();
            return executeColum;
        }//from  w  w w.  j  a v a  2s.  com
    }, true);
    return i;
}

From source file:com.allinfinance.commquery.dao.CommQueryDAO.java

License:Open Source License

public List findBySQLQuery(final String sql, final int begin, final int count) {
    return getHibernateTemplate().executeFind(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createSQLQuery(sql);
            if (begin >= 0) {
                query.setFirstResult(begin);
                query.setMaxResults(count);
            }/*from   ww w.  j av a2 s  . co  m*/
            return query.list();
        }
    });
}

From source file:com.allinfinance.commquery.dao.CommQueryDAO.java

License:Open Source License

public List findBySQLQuery(final String sql) {
    List data = getHibernateTemplate().executeFind(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createSQLQuery(sql);
            return query.list();
        }//from w  w  w . j a  va2s . c om
    });
    return data;
}

From source file:com.allinfinance.commquery.dao.CommQueryDAO.java

License:Open Source License

public List findBySQLQuery(final String sql, final Map map) {
    List data = getHibernateTemplate().executeFind(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createSQLQuery(sql);
            Iterator iter = map.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next().toString();
                Object obj = map.get(key);
                String[] keys = query.getNamedParameters();
                for (int i = 0; i < keys.length; i++) {
                    if (key != null && key.equals(keys[i])) {
                        if (obj instanceof String) {
                            query.setString(key, obj.toString());
                        }/*  ww  w.ja v  a2 s. c o m*/
                        if (obj instanceof Number) {
                            query.setInteger(key, Integer.parseInt(obj.toString()));
                        }
                        if (obj instanceof BigDecimal) {
                            query.setBigDecimal(key, (BigDecimal) obj);
                        }
                        if (obj instanceof List) {
                            query.setParameterList(key, (List) obj);
                        }
                    }
                }
            }
            return query.list();
        }
    });
    return data;
}

From source file:com.allinfinance.commquery.dao.CommQueryDAO.java

License:Open Source License

public List findBySQLQuery(final String sql, final int begin, final int count, final Map map) {
    return getHibernateTemplate().executeFind(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createSQLQuery(sql);
            Iterator iter = map.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next().toString();
                Object obj = map.get(key);
                String[] keys = query.getNamedParameters();
                for (int i = 0; i < keys.length; i++) {
                    if (key != null && key.equals(keys[i])) {
                        if (obj instanceof String) {
                            query.setString(key, obj.toString());
                        }// www. ja v a  2  s .  co m
                        if (obj instanceof Number) {
                            query.setInteger(key, Integer.parseInt(obj.toString()));
                        }
                        if (obj instanceof BigDecimal) {
                            query.setBigDecimal(key, (BigDecimal) obj);
                        }
                        if (obj instanceof List) {
                            query.setParameterList(key, (List) obj);
                        }
                    }
                }
            }
            if (begin >= 0) {
                query.setFirstResult(begin);
                query.setMaxResults(count);
            }
            return query.list();
        }
    });
}

From source file:com.allinfinance.commquery.dao.CommQueryDAO.java

License:Open Source License

public String findCountBySQLQuery(final String countSql) {
    List data = getHibernateTemplate().executeFind(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createSQLQuery(countSql);
            return query.list();
        }//from w w  w.  jav a  2s. c  o m
    });
    if (data == null || data.get(0) != null)
        return data.get(0).toString();
    return null;
}

From source file:com.allinfinance.commquery.dao.CommQueryDAO.java

License:Open Source License

public String findCountBySQLQuery(final String countSql, final Map map) {
    List data = getHibernateTemplate().executeFind(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createSQLQuery(countSql);
            Iterator iter = map.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next().toString();
                Object obj = map.get(key);
                String[] keys = query.getNamedParameters();
                for (int i = 0; i < keys.length; i++) {
                    if (key != null && key.equals(keys[i])) {
                        if (obj instanceof String) {
                            query.setString(key, obj.toString());
                        }//from  w  ww.  j ava 2 s . c  o m
                        if (obj instanceof Number) {
                            query.setInteger(key, Integer.parseInt(obj.toString()));
                        }
                        if (obj instanceof BigDecimal) {
                            query.setBigDecimal(key, (BigDecimal) obj);
                        }
                        if (obj instanceof List) {
                            query.setParameterList(key, (List) obj);
                        }
                    }
                }
            }
            return query.list();
        }
    });
    return data.get(0).toString();
}

From source file:com.amalto.core.storage.hibernate.HibernateStorage.java

License:Open Source License

@SuppressWarnings("rawtypes")
@Override/*from w  ww .j a va  2s . c om*/
public void delete(Expression userQuery) {
    Session session = this.getCurrentSession();
    try {
        storageClassLoader.bind(Thread.currentThread());
        // Session session = factory.getCurrentSession();
        userQuery = userQuery.normalize(); // First do a normalize for correct optimization detection.
        // Check if optimized delete for one type (and no filter) is applicable
        if (userQuery instanceof Select) {
            Select select = (Select) userQuery;
            List<ComplexTypeMetadata> types = select.getTypes();
            if (types.size() == 1 && select.getCondition() == null) {
                FlushMode previousFlushMode = session.getFlushMode();
                try {
                    session.setFlushMode(FlushMode.ALWAYS); // Force Hibernate to actually send SQL query to
                                                            // database during delete.
                    ComplexTypeMetadata mainType = types.get(0);
                    TypeMapping mapping = mappingRepository.getMappingFromUser(mainType);
                    // Compute (and eventually sort) types to delete
                    List<ComplexTypeMetadata> typesToDelete;
                    MetadataRepository internalRepository = typeMappingRepository.getInternalRepository();
                    if (mapping instanceof ScatteredTypeMapping) {
                        MetadataVisitor<List<ComplexTypeMetadata>> transitiveClosure = new TypeTransitiveClosure();
                        List<ComplexTypeMetadata> typeClosure = mapping.getDatabase().accept(transitiveClosure);
                        typesToDelete = MetadataUtils.sortTypes(internalRepository, typeClosure);
                    } else {
                        Collection<ComplexTypeMetadata> subTypes = mapping.getDatabase().getSubTypes();
                        if (subTypes.isEmpty()) {
                            typesToDelete = Collections.singletonList(mapping.getDatabase());
                        } else {
                            typesToDelete = new ArrayList<ComplexTypeMetadata>(subTypes.size() + 1);
                            typesToDelete.add(mapping.getDatabase());
                            typesToDelete.addAll(subTypes);
                        }
                    }
                    Map<ComplexTypeMetadata, Map<String, List>> recordsToDeleteMap = new HashMap<ComplexTypeMetadata, Map<String, List>>();
                    for (ComplexTypeMetadata typeToDelete : typesToDelete) {
                        InboundReferences inboundReferences = new InboundReferences(typeToDelete);
                        Set<ReferenceFieldMetadata> references = internalRepository.accept(inboundReferences);
                        // Empty values from intermediate tables to this non instantiable type and unset inbound
                        // references
                        if (typeToDelete.equals(mainType)) {
                            for (ReferenceFieldMetadata reference : references) {
                                if (reference.isMany()) {
                                    // No need to check for mandatory collections of references since constraint
                                    // cannot be expressed in db schema
                                    String formattedTableName = tableResolver.getCollectionTable(reference);
                                    session.createSQLQuery("delete from " + formattedTableName).executeUpdate(); //$NON-NLS-1$
                                } else {
                                    String referenceTableName = tableResolver
                                            .get(reference.getContainingType());
                                    if (referenceTableName.startsWith("X_ANONYMOUS")) { //$NON-NLS-1$
                                        session.createSQLQuery("delete from " + referenceTableName) //$NON-NLS-1$
                                                .executeUpdate();
                                    }
                                }
                            }
                        } else {
                            for (ReferenceFieldMetadata reference : references) {
                                if (reference.getContainingType().equals(mainType)) {
                                    HashMap<String, List> fieldsCondition = new HashMap<>();
                                    if (reference.isMany()) {
                                        // No need to check for mandatory collections of references since constraint
                                        // cannot
                                        // be expressed in db schema
                                        String formattedTableName = tableResolver.getCollectionTable(reference);
                                        session.createSQLQuery("delete from " + formattedTableName) //$NON-NLS-1$
                                                .executeUpdate();
                                    } else {
                                        String referenceTableName = tableResolver
                                                .get(reference.getContainingType());
                                        if (reference.getReferencedField() instanceof CompoundFieldMetadata) {
                                            FieldMetadata[] fields = ((CompoundFieldMetadata) reference
                                                    .getReferencedField()).getFields();
                                            for (FieldMetadata field : fields) {
                                                List list = session.createSQLQuery("select " //$NON-NLS-1$
                                                        + tableResolver.get(field, reference.getName())
                                                        + " from " //$NON-NLS-1$
                                                        + referenceTableName).list();
                                                if (list == null || list.isEmpty()) {
                                                    continue;
                                                } else {
                                                    fieldsCondition.put(
                                                            tableResolver.get(reference.getReferencedField()),
                                                            list);
                                                }
                                            }
                                        } else {
                                            List list = session.createSQLQuery("select " //$NON-NLS-1$
                                                    + tableResolver.get(reference.getReferencedField(),
                                                            reference.getName())
                                                    + " from " + referenceTableName).list(); //$NON-NLS-1$
                                            if (list == null || list.isEmpty()) {
                                                continue;
                                            } else {
                                                fieldsCondition.put(
                                                        tableResolver.get(reference.getReferencedField()),
                                                        list);
                                            }
                                        }
                                        recordsToDeleteMap.put(typeToDelete, fieldsCondition);
                                    }
                                }
                            }
                        }
                    }
                    deleteData(mapping.getDatabase(), new HashMap<String, List>(), mapping);
                    for (Map.Entry<ComplexTypeMetadata, Map<String, List>> entry : recordsToDeleteMap
                            .entrySet()) {
                        // Empty values in type isMany=true reference
                        deleteData(entry.getKey(), entry.getValue(), mapping);
                    }
                } finally {
                    session.setFlushMode(previousFlushMode);
                }
                return;
            }
        }
        // Generic fall back for deletions (filter)
        if (userQuery instanceof Select) {
            ((Select) userQuery).setForUpdate(true);
        }
        Iterable<DataRecord> records = internalFetch(session, userQuery,
                Collections.<ResultsCallback>emptySet());
        for (DataRecord currentDataRecord : records) {
            ComplexTypeMetadata currentType = currentDataRecord.getType();
            List<ComplexTypeMetadata> types = new ArrayList<>();
            if (userQuery instanceof Select) {
                types.addAll(((Select) userQuery).getTypes());
            }
            if (types.isEmpty() || types.contains(currentType)) {
                TypeMapping mapping = mappingRepository.getMappingFromUser(currentType);
                if (mapping == null) {
                    throw new IllegalArgumentException(
                            "Type '" + currentType.getName() + "' does not have a database mapping."); //$NON-NLS-1$ //$NON-NLS-2$
                }
                Class<?> clazz = storageClassLoader.getClassFromType(mapping.getDatabase());

                Serializable idValue;
                Collection<FieldMetadata> keyFields = currentType.getKeyFields();
                if (keyFields.size() == 1) {
                    idValue = (Serializable) currentDataRecord.get(keyFields.iterator().next());
                } else {
                    List<Object> compositeIdValues = new LinkedList<Object>();
                    for (FieldMetadata keyField : keyFields) {
                        compositeIdValues.add(currentDataRecord.get(keyField));
                    }
                    idValue = ObjectDataRecordConverter.createCompositeId(storageClassLoader, clazz,
                            compositeIdValues);
                }

                Wrapper object = (Wrapper) session.get(clazz, idValue, LockOptions.READ);
                if (object != null) {
                    session.delete(object);
                } else {
                    LOGGER.warn("Instance of type '" + currentType.getName() + "' and ID '" + idValue.toString() //$NON-NLS-1$ //$NON-NLS-2$
                            + "' has already been deleted within same transaction."); //$NON-NLS-1$
                }
            }
        }
    } catch (ConstraintViolationException e) {
        throw new com.amalto.core.storage.exception.ConstraintViolationException(e);
    } catch (HibernateException e) {
        throw new RuntimeException(e);
    } finally {
        this.releaseSession();
        storageClassLoader.unbind(Thread.currentThread());
    }
}