Java Code Examples for org.hibernate.Session#setDefaultReadOnly()

The following examples show how to use org.hibernate.Session#setDefaultReadOnly() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@GET
public Object db() throws InterruptedException, ExecutionException {
	Callable<World> callable = () -> {
		EntityManager em = emf.createEntityManager();
		Session session = em.unwrap(Session.class);
		session.setDefaultReadOnly(true);
		try {
			return (World) session.byId(World.class).load(randomWorld());
		} finally {
			session.close();
		}
	};
	Future<World> futureWorld = Common.EXECUTOR.submit(callable);
	return futureWorld.get();
}
 
Example 2
@GET
public Object db() throws InterruptedException, ExecutionException {
	Callable<World> callable = () -> {
		EntityManager em = emf.createEntityManager();
		Session session = em.unwrap(Session.class);
		session.setDefaultReadOnly(true);
		try {
			return (World) session.byId(World.class).load(randomWorld());
		} finally {
			session.close();
		}
	};
	Future<World> futureWorld = Common.EXECUTOR.submit(callable);
	return futureWorld.get();
}
 
Example 3
private Session getSession() {
    Session session = sessionFactory.openSession();
    LOG.debug("Database session acquired: " + session);

    if (readonly) {
        session.setDefaultReadOnly(true);
    }

    return session;
}
 
Example 4
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	Session session = getSession(entityManager);

	if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
		session.getTransaction().setTimeout(definition.getTimeout());
	}

	boolean isolationLevelNeeded = (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT);
	Integer previousIsolationLevel = null;
	Connection preparedCon = null;

	if (isolationLevelNeeded || definition.isReadOnly()) {
		if (this.prepareConnection) {
			preparedCon = HibernateConnectionHandle.doGetConnection(session);
			previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(preparedCon, definition);
		}
		else if (isolationLevelNeeded) {
			throw new InvalidIsolationLevelException(getClass().getSimpleName() +
					" does not support custom isolation levels since the 'prepareConnection' flag is off.");
		}
	}

	// Standard JPA transaction begin call for full JPA context setup...
	entityManager.getTransaction().begin();

	// Adapt flush mode and store previous isolation level, if any.
	FlushMode previousFlushMode = prepareFlushMode(session, definition.isReadOnly());
	if (definition instanceof ResourceTransactionDefinition &&
			((ResourceTransactionDefinition) definition).isLocalResource()) {
		// As of 5.1, we explicitly optimize for a transaction-local EntityManager,
		// aligned with native HibernateTransactionManager behavior.
		previousFlushMode = null;
		if (definition.isReadOnly()) {
			session.setDefaultReadOnly(true);
		}
	}
	return new SessionTransactionData(session, previousFlushMode, preparedCon, previousIsolationLevel);
}
 
Example 5
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	Session session = getSession(entityManager);

	if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
		session.getTransaction().setTimeout(definition.getTimeout());
	}

	boolean isolationLevelNeeded = (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT);
	Integer previousIsolationLevel = null;
	Connection preparedCon = null;

	if (isolationLevelNeeded || definition.isReadOnly()) {
		if (this.prepareConnection) {
			preparedCon = HibernateConnectionHandle.doGetConnection(session);
			previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(preparedCon, definition);
		}
		else if (isolationLevelNeeded) {
			throw new InvalidIsolationLevelException(getClass().getSimpleName() +
					" does not support custom isolation levels since the 'prepareConnection' flag is off.");
		}
	}

	// Standard JPA transaction begin call for full JPA context setup...
	entityManager.getTransaction().begin();

	// Adapt flush mode and store previous isolation level, if any.
	FlushMode previousFlushMode = prepareFlushMode(session, definition.isReadOnly());
	if (definition instanceof ResourceTransactionDefinition &&
			((ResourceTransactionDefinition) definition).isLocalResource()) {
		// As of 5.1, we explicitly optimize for a transaction-local EntityManager,
		// aligned with native HibernateTransactionManager behavior.
		previousFlushMode = null;
		if (definition.isReadOnly()) {
			session.setDefaultReadOnly(true);
		}
	}
	return new SessionTransactionData(session, previousFlushMode, preparedCon, previousIsolationLevel);
}
 
Example 6
@GET
@Path("/updates")
public World[] updates(@QueryParam("queries") String queriesParam) throws InterruptedException,
		ExecutionException {
	final int queries = getQueries(queriesParam);
	final World[] worlds = new World[queries];

	Callable<World[]> callable = () -> {
		Session session = emf.createEntityManager().unwrap(Session.class);
		session.setDefaultReadOnly(false);
		Transaction txn = session.beginTransaction();

		try {
			// using write batching. See the data source properties provided
			// in the configuration file

			// 1. Read and update the entities from the DB
			for (int i = 0; i < queries; i++) {
				final World world = (World) session.byId(World.class).load(randomWorld());
				world.setRandomNumber(randomWorld());
				worlds[i] = world;
			}

			// 2. Sort the array to prevent transaction deadlock in the DB
			Arrays.sort(worlds, Comparator.comparingInt(World::getId));

			// 3. Actually save the entities
			for (int i = 0; i < worlds.length; i++) {
				session.persist(worlds[i]);
			}

			session.flush();
			session.clear();
			txn.commit();

			return worlds;
		} catch (RuntimeException e) {
			if (txn != null && txn.isActive())
				txn.rollback();
			throw e;
		} finally {
			session.close();
		}
	};
	Future<World[]> futureWorlds = Common.EXECUTOR.submit(callable);
	return futureWorlds.get();
}
 
Example 7
@GET
@Path("/updates")
public World[] updates(@QueryParam("queries") String queriesParam) throws InterruptedException,
		ExecutionException {
	final int queries = getQueries(queriesParam);
	final World[] worlds = new World[queries];

	Callable<World[]> callable = () -> {
		Session session = emf.createEntityManager().unwrap(Session.class);
		session.setDefaultReadOnly(false);
		Transaction txn = session.beginTransaction();

		try {
			// using write batching. See the data source properties provided
			// in the configuration file

			// 1. Read and update the entities from the DB
	        final AtomicInteger ii = new AtomicInteger(0);
	        ThreadLocalRandom.current().ints(1, 10001).distinct().limit(queries).forEach(
	            (randomValue)->{
	            		final World world = (World) session.byId(World.class).load(randomValue);
	            		world.setRandomNumber(randomWorld());
	            		worlds[ii.getAndAdd(1)]=world;
	            	}
	        );

	        // 2. Sort the array to prevent transaction deadlock in the DB
			Arrays.sort(worlds, Comparator.comparingInt(World::getId));

			// 3. Actually save the entities
			for (int i = 0; i < worlds.length; i++) {
				session.persist(worlds[i]);
			}

			session.flush();
			session.clear();
			txn.commit();

			return worlds;
		} catch (RuntimeException e) {
			if (txn != null && txn.isActive())
				txn.rollback();
			throw e;
		} finally {
			session.close();
		}
	};
	Future<World[]> futureWorlds = Common.EXECUTOR.submit(callable);
	return futureWorlds.get();
}
 
Example 8
/**
 * Verify the imported dump.
 * @return Number of checked objects. This number is negative if any error occurs (at least one object wasn't imported successfully).
 */
public int verifyDump(final XStreamSavingConverter xstreamSavingConverter)
{
  final SessionFactory sessionFactory = hibernate.getSessionFactory();
  Session session = null;
  boolean hasError = false;
  try {
    session = sessionFactory.openSession(EmptyInterceptor.INSTANCE);
    session.setDefaultReadOnly(true);
    int counter = 0;
    for (final Map.Entry<Class< ? >, List<Object>> entry : xstreamSavingConverter.getAllObjects().entrySet()) {
      final List<Object> objects = entry.getValue();
      final Class< ? > entityClass = entry.getKey();
      if (objects == null) {
        continue;
      }
      for (final Object obj : objects) {
        if (HibernateUtils.isEntity(obj.getClass()) == false) {
          continue;
        }
        final Serializable id = HibernateUtils.getIdentifier(obj);
        if (id == null) {
          // Can't compare this object without identifier.
          continue;
        }
        // log.info("Testing object: " + obj);
        final Object databaseObject = session.get(entityClass, id, LockOptions.READ);
        Hibernate.initialize(databaseObject);
        final boolean equals = equals(obj, databaseObject, true);
        if (equals == false) {
          log.error("Object not sucessfully imported! xml object=[" + obj + "], data base=[" + databaseObject + "]");
          hasError = true;
        }
        ++counter;
      }
    }
    for (final HistoryEntry historyEntry : xstreamSavingConverter.getHistoryEntries()) {
      final Class< ? > type = xstreamSavingConverter.getClassFromHistoryName(historyEntry.getClassName());
      final Object o = type != null ? session.get(type, historyEntry.getEntityId()) : null;
      if (o == null) {
        log.warn("A corrupted history entry found (entity of class '"
            + historyEntry.getClassName()
            + "' with id "
            + historyEntry.getEntityId()
            + " not found: "
            + historyEntry
            + ". This doesn't affect the functioning of ProjectForge, this may result in orphaned history entries.");
        hasError = true;
      }
      ++counter;
    }
    if (hasError == true) {
      log.fatal("*********** A inconsistency in the import was found! This may result in a data loss or corrupted data! Please retry the import. "
          + counter
          + " entries checked.");
      return -counter;
    }
    log.info("Data-base import successfully verified: " + counter + " entries checked.");
    return counter;
  } finally {
    if (session != null) {
      session.close();
    }
  }
}
 
Example 9
/**
 * @see io.dropwizard.hibernate.UnitOfWorkAspect#configureSession()
 */
private void configureSession(Session session, UnitOfWork unitOfWork) {
    session.setDefaultReadOnly(unitOfWork.readOnly());
    session.setCacheMode(unitOfWork.cacheMode());
    session.setHibernateFlushMode(unitOfWork.flushMode());
}