Example usage for org.hibernate LockOptions READ

List of usage examples for org.hibernate LockOptions READ

Introduction

In this page you can find the example usage for org.hibernate LockOptions READ.

Prototype

LockOptions READ

To view the source code for org.hibernate LockOptions READ.

Click Source Link

Document

Represents LockMode.READ (timeout + scope do not apply).

Usage

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

License:Open Source License

@SuppressWarnings("rawtypes")
@Override/*from  www. ja  va  2 s  .  c o  m*/
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());
    }
}

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

License:Open Source License

@Override
public void delete(DataRecord record) {
    Session session = this.getCurrentSession();
    try {//www  . j  a  va  2  s . c o  m
        storageClassLoader.bind(Thread.currentThread());
        // Session session = factory.getCurrentSession();
        ComplexTypeMetadata currentType = record.getType();
        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) record.get(keyFields.iterator().next());
        } else {
            List<Object> compositeIdValues = new LinkedList<Object>();
            for (FieldMetadata keyField : keyFields) {
                compositeIdValues.add(record.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());
    }
}

From source file:com.github.jmnarloch.hstreams.internal.QueryDelegateTest.java

License:Apache License

@Test
public void testSetLockOptions() throws Exception {

    // given//  w  w  w.j a va  2 s  .  com
    final LockOptions lockOptions = LockOptions.READ;

    // then
    verifyMethodCall(q -> q.setLockOptions(lockOptions));
}

From source file:com.github.jmnarloch.hstreams.internal.SessionDelegateTest.java

License:Apache License

@Test
public void testGetOptional1() throws Exception {

    // given//ww  w  .ja v  a 2s.c  om
    final Class<Object> clazz = Object.class;
    final long id = 1l;
    final LockOptions lockOptions = LockOptions.READ;

    // when
    instance.getOptional(clazz, id, lockOptions);

    // then
    Mockito.verify(session).get(clazz, id, lockOptions);
}

From source file:com.github.jmnarloch.hstreams.internal.SessionDelegateTest.java

License:Apache License

@Test
public void testGetOptional3() throws Exception {

    // given//  w  w w .  ja va 2s  .c om
    final String entityName = "entityName";
    final long id = 1l;
    final LockOptions lockOptions = LockOptions.READ;

    // when
    instance.getOptional(entityName, id, lockOptions);

    // then
    Mockito.verify(session).get(entityName, id, lockOptions);
}

From source file:com.github.jmnarloch.hstreams.internal.SessionDelegateTest.java

License:Apache License

@Test
public void testLoad2() throws Exception {

    // given/*from   w w  w . ja v a 2s .c om*/
    final Class<Object> clazz = Object.class;
    final long id = 1l;
    final LockOptions lockOptions = LockOptions.READ;

    // then
    verifyMethodCall(s -> s.load(clazz, id, lockOptions));
}

From source file:com.github.jmnarloch.hstreams.internal.SessionDelegateTest.java

License:Apache License

@Test
public void testLoad5() throws Exception {

    // given//from  ww w. jav a 2 s.  c o  m
    final String entityName = "entityName";
    final long id = 1l;
    final LockOptions lockOptions = LockOptions.READ;

    // then
    verifyMethodCall(s -> s.load(entityName, id, lockOptions));
}

From source file:com.github.jmnarloch.hstreams.internal.SessionDelegateTest.java

License:Apache License

@Test
public void testBuildLockRequest() throws Exception {

    // given/*from w ww  .j a v  a  2 s  .  c  o m*/
    final LockOptions lockOptions = LockOptions.READ;

    // then
    verifyMethodCall(s -> s.buildLockRequest(lockOptions));
}

From source file:com.github.jmnarloch.hstreams.internal.SessionDelegateTest.java

License:Apache License

@Test
public void testRefresh3() throws Exception {

    // given/*w w w.  j  a  v  a 2 s .com*/
    final Object object = new Object();
    final LockOptions lockOptions = LockOptions.READ;

    // then
    verifyMethodCall(s -> s.refresh(object, lockOptions));
}

From source file:com.github.jmnarloch.hstreams.internal.SessionDelegateTest.java

License:Apache License

@Test
public void testRefresh4() throws Exception {

    // given//from   www .  j a v  a 2s .c om
    final Object object = new Object();
    final String entityName = "entityName";
    final LockOptions lockOptions = LockOptions.READ;

    // then
    verifyMethodCall(s -> s.refresh(entityName, object, lockOptions));
}