List of usage examples for org.hibernate Session isReadOnly
boolean isReadOnly(Object entityOrProxy);
From source file:com.amalto.core.storage.hibernate.HibernateStorage.java
License:Open Source License
@Override public void update(Iterable<DataRecord> records) { assertPrepared();// w w w . j a v a 2 s . c o m Session session = this.getCurrentSession(); try { storageClassLoader.bind(Thread.currentThread()); DataRecordConverter<Object> converter = new ObjectDataRecordConverter(storageClassLoader, session); for (DataRecord currentDataRecord : records) { TypeMapping mapping = mappingRepository.getMappingFromUser(currentDataRecord.getType()); Wrapper o = (Wrapper) converter.convert(currentDataRecord, mapping); if (session.contains(o) && session.isReadOnly(o)) { // A read only instance for an update? // Session#setReadOnly(...) does not always work as expected (especially in case of compound keys // see TMDM-7014). session.evict(o); o = (Wrapper) converter.convert(currentDataRecord, mapping); } DataRecordMetadata recordMetadata = currentDataRecord.getRecordMetadata(); Map<String, String> recordProperties = recordMetadata.getRecordProperties(); if (!ObjectUtils.equals(recordMetadata.getTaskId(), o.taskId())) { o.taskId(recordMetadata.getTaskId()); } for (Map.Entry<String, String> currentProperty : recordProperties.entrySet()) { String key = currentProperty.getKey(); String value = currentProperty.getValue(); ComplexTypeMetadata database = mapping.getDatabase(); if (database.hasField(key)) { Object convertedValue = StorageMetadataUtils.convert(value, database.getField(key)); if (!ObjectUtils.equals(convertedValue, o.get(key))) { o.set(key, convertedValue); } } else { throw new IllegalArgumentException("Can not store value '" + key //$NON-NLS-1$ + "' because there is no database field '" + key + "' in type '" + mapping.getName() //$NON-NLS-1$ //$NON-NLS-2$ + "' (storage is '" + toString() + "')"); //$NON-NLS-1$ //$NON-NLS-2$ } } session.saveOrUpdate(o); if (FLUSH_ON_LOAD && session.getStatistics().getEntityCount() % batchSize == 0) { // Periodically flush objects to avoid using too much memory. session.flush(); } } } catch (ConstraintViolationException e) { throw new com.amalto.core.storage.exception.ConstraintViolationException(e); } catch (PropertyValueException e) { throw new RuntimeException("Invalid value in record to update.", e); //$NON-NLS-1$ } catch (NonUniqueObjectException e) { throw new RuntimeException("Attempted to update multiple times same record within same transaction.", //$NON-NLS-1$ e); } catch (Exception e) { throw new RuntimeException("Exception occurred during update.", e); //$NON-NLS-1$ } finally { this.releaseSession(); storageClassLoader.unbind(Thread.currentThread()); } }
From source file:com.amalto.core.storage.hibernate.HibernateStorageTransaction.java
License:Open Source License
/** * Dumps all current entities in <code>session</code> using data model information from <code>storage</code>. * * @param session The Hibernate session that failed to be committed. * @param storage A {@link com.amalto.core.storage.hibernate.HibernateStorage} that can be used to retrieve metadata information for all objects in * <code>session</code>. *///from ww w.j av a2 s . c o m private static void dumpTransactionContent(Session session, HibernateStorage storage) { Level currentLevel = Level.INFO; if (LOGGER.isEnabledFor(currentLevel)) { Set<EntityKey> failedKeys = new HashSet<>(session.getStatistics().getEntityKeys()); // Copy content to avoid concurrent modification issues. int i = 1; ObjectDataRecordReader reader = new ObjectDataRecordReader(); MappingRepository mappingRepository = storage.getTypeEnhancer().getMappings(); StorageClassLoader classLoader = storage.getClassLoader(); DataRecordXmlWriter writer = new DataRecordXmlWriter(); ResettableStringWriter xmlContent = new ResettableStringWriter(); for (EntityKey failedKey : failedKeys) { String entityTypeName = StringUtils.substringAfterLast(failedKey.getEntityName(), "."); //$NON-NLS-1$ LOGGER.log(currentLevel, "Entity #" + i++ + " (type=" + entityTypeName + ", id=" + failedKey.getIdentifier() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ try { storage.getClassLoader().bind(Thread.currentThread()); Wrapper o = (Wrapper) ((SessionImpl) session).getPersistenceContext().getEntity(failedKey); if (!session.isReadOnly(o)) { if (o != null) { ComplexTypeMetadata type = classLoader .getTypeFromClass(classLoader.loadClass(failedKey.getEntityName())); if (type != null) { DataRecord record = reader.read(mappingRepository.getMappingFromDatabase(type), o); writer.write(record, xmlContent); LOGGER.log(currentLevel, xmlContent + "\n(taskId='" + o.taskId() + "', timestamp='" //$NON-NLS-1$//$NON-NLS-2$ + o.timestamp() + "')"); //$NON-NLS-1$ } else { LOGGER.warn("Could not find data model type for object " + o); //$NON-NLS-1$ } } else { LOGGER.warn("Could not find an object for entity " + failedKey); //$NON-NLS-1$ } } } catch (ObjectNotFoundException missingRefException) { LOGGER.log(currentLevel, "Can not log entity: contains a unresolved reference to '" //$NON-NLS-1$ + missingRefException.getEntityName() + "' with id '" //$NON-NLS-1$ + missingRefException.getIdentifier() + "'"); //$NON-NLS-1$ } catch (Exception serializationException) { LOGGER.log(currentLevel, "Failed to log entity content for type " + entityTypeName //$NON-NLS-1$ + " (enable DEBUG for exception details)."); //$NON-NLS-1$ if (LOGGER.isDebugEnabled()) { LOGGER.debug("Serialization exception occurred.", serializationException); //$NON-NLS-1$ } } finally { xmlContent.reset(); storage.getClassLoader().unbind(Thread.currentThread()); } if (i > TRANSACTION_DUMP_MAX) { if (!LOGGER.isDebugEnabled()) { int more = failedKeys.size() - i; if (more > 0) { LOGGER.log(currentLevel, "and " + more + " more... (enable DEBUG for full dump)"); //$NON-NLS-1$ //$NON-NLS-2$ } return; } else { currentLevel = Level.DEBUG; // Continue the dump but with a DEBUG level } } } } }
From source file:com.mercatis.lighthouse3.persistence.commons.hibernate.UnitOfWorkImplementation.java
License:Apache License
public void setReadOnly(Object o, boolean readOnly) { Session session = threadLocalSessions.get(); if (session == null) { return;/*from ww w .j a va 2 s .com*/ } if (session.contains(o) && session.isReadOnly(o) != readOnly) { if (log.isDebugEnabled()) { log.debug( "UnitOfWork: SetReadOnly: " + readOnly + ", Session: " + System.identityHashCode(session)); } session.setReadOnly(o, readOnly); } }