List of usage examples for javax.persistence EntityManager unwrap
public <T> T unwrap(Class<T> cls);
From source file:org.eclipse.jubula.client.core.persistence.Persistor.java
/** * Installs the DB scheme used by Jubula. * // w w w . ja va 2 s . co m * @param entityManagerFactory * The factory to use to create the entity manager in which the * installation will occur. * * @return <code>true</code> if the installation was successful. Otherwise, * <code>false</code>. * @throws PMDatabaseConfException * if the scheme couldn't be installed * @throws JBException * in case of configuration problems */ private static boolean installDbScheme(EntityManagerFactory entityManagerFactory) throws PMDatabaseConfException, JBException { EntityManager em = null; try { em = entityManagerFactory.createEntityManager(); SchemaManager schemaManager = new SchemaManager(em.unwrap(ServerSession.class)); schemaManager.replaceDefaultTables(); createOrUpdateDBVersion(em); createOrUpdateDBGuard(em); return true; } catch (PersistenceException e) { Throwable rootCause = ExceptionUtils.getRootCause(e); if (rootCause instanceof SQLException) { if (("08001").equals(((SQLException) rootCause).getSQLState())) { //$NON-NLS-1$ log.error(Messages.TheDBAllreadyUseAnotherProcess, e); throw new JBException(rootCause.getMessage(), MessageIDs.E_DB_IN_USE); } log.error(Messages.NoOrWrongUsernameOrPassword, e); throw new JBException(e.getMessage(), MessageIDs.E_NO_DB_CONNECTION); } final String msg = Messages.ProblemInstallingDBScheme + StringConstants.DOT; log.error(msg); throw new PMDatabaseConfException(msg, MessageIDs.E_NO_DB_SCHEME); } finally { if (em != null) { try { em.close(); } catch (Throwable e) { // ignore } } } }
From source file:org.springframework.orm.jpa.vendor.HibernateJpaDialect.java
protected Session getSession(EntityManager entityManager) { return entityManager.unwrap(Session.class); }
From source file:richtercloud.document.scanner.it.BlobStorageIT.java
@Test @Ignore/*w ww. j a v a 2 s . c om*/ //fails due to //``` //[EL Warning]: 2017-07-31 00:11:40.03--UnitOfWork(178575564)--Exception [EclipseLink-32] (Eclipse Persistence Services - 2.6.4.v20160829-44060b6): org.eclipse.persistence.exceptions.DescriptorException //Exception Description: Trying to set value [[B@44550792] for instance variable [data] of type [java.sql.Blob] in the object. The specified object is not an instance of the class or interface declaring the underlying field, or an unwrapping conversion has failed. //Internal Exception: java.lang.IllegalArgumentException: Can not set java.sql.Blob field richtercloud.document.scanner.it.entities.EntityBlob.data to [B //Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[data-->ENTITYBLOB.DATA] //Descriptor: RelationalDescriptor(richtercloud.document.scanner.it.entities.EntityBlob --> [DatabaseTable(ENTITYBLOB)]) //``` public void testBlobStorage() throws IOException, SQLException, StorageConfValidationException, StorageCreationException, InterruptedException, StorageException, FieldOrderValidationException { LOGGER.info("testBlobStorage"); PersistenceStorage<Long> storage = null; try { IssueHandler issueHandler = new LoggerIssueHandler(LOGGER); Set<Class<?>> entityClasses = new HashSet<>(Arrays.asList(EntityImageWrapper.class)); File databaseDir = Files.createTempDirectory("document-scanner-blob-it").toFile(); FileUtils.forceDelete(databaseDir); //databaseDir mustn't exist for MySQL File schemeChecksumFile = File.createTempFile("document-scanner-blob-it", null); schemeChecksumFile.delete(); String persistenceUnitName = "document-scanner-it"; String username = "document-scanner"; String password = "document-scanner"; String databaseName = "document-scanner"; //Testing PostgreSQL doesn't make sense because it doesn't implement //java.sql.Connection.createBlob (see persistence.xml in //document-scanner) // PostgresqlAutoPersistenceStorageConf storageConf = new PostgresqlAutoPersistenceStorageConf(entityClasses, // username, // schemeChecksumFile, // databaseDir.getAbsolutePath()); //Apache Derby is extremely slow // DerbyEmbeddedPersistenceStorageConf storageConf = new DerbyEmbeddedPersistenceStorageConf(entityClasses, // databaseName, // schemeChecksumFile); File myCnfFile = File.createTempFile("document-scanner-it-blob-it", null); myCnfFile.delete(); //need to delete in order to trigger creation of //my.cnf MySQLAutoPersistenceStorageConf storageConf = new MySQLAutoPersistenceStorageConf(entityClasses, "localhost", //hostname username, databaseName, databaseDir.getAbsolutePath(), schemeChecksumFile); storageConf.setBaseDir( new File(DocumentScannerConf.CONFIG_DIR_DEFAULT, "mysql-5.7.16-linux-glibc2.5-x86_64") .getAbsolutePath()); storageConf.setMyCnfFilePath(myCnfFile.getAbsolutePath()); FieldRetriever fieldRetriever = new JPAOrderedCachedFieldRetriever( Constants.QUERYABLE_AND_EMBEDDABLE_CLASSES); storage = new MySQLAutoPersistenceStorage(storageConf, persistenceUnitName, 1, //parallelQueryCount issueHandler, fieldRetriever); storage.start(); long randomSeed = System.currentTimeMillis(); LOGGER.debug(String.format("random seed is %d", randomSeed)); Random random = new Random(randomSeed); int entityCount = 20; for (int i = 0; i < entityCount; i++) { int mbSize = random.nextInt(256); //256 MB max. int byteCount = 1024 * 1024 * mbSize; LOGGER.debug(String.format("generating %d MB random bytes", mbSize)); byte[] largeRandomBytes = new byte[byteCount]; random.nextBytes(largeRandomBytes); EntityManager entityManager = storage.retrieveEntityManager(); entityManager.getTransaction().begin(); Blob blob = entityManager.unwrap(Connection.class).createBlob(); OutputStream blobOutputStream = blob.setBinaryStream(1 //pos (begin //at 1) ); ByteArrayInputStream largeRandomBytesInputStream = new ByteArrayInputStream(largeRandomBytes); IOUtils.copy(largeRandomBytesInputStream, blobOutputStream); EntityBlob entity1 = new EntityBlob(blob); LOGGER.debug(String.format("storing large binary entity (%d of %d)", i, entityCount)); storage.store(entity1); entityManager.getTransaction().commit(); } //shutdown and restart storage in order to simulate persistence //across application starts storage.shutdown(); Thread.sleep(5000); //workaround for remaining storage process after shutdown storage = new MySQLAutoPersistenceStorage(storageConf, persistenceUnitName, 1, //parallelQueryCount issueHandler, fieldRetriever); storage.start(); LOGGER.debug("querying large binary entity"); List<EntityBlob> queryResults = storage.runQueryAll(EntityBlob.class); LOGGER.debug(String.format("query completed with %d results", queryResults.size())); int i = 0; for (EntityBlob queryResult : queryResults) { int mbSize = (int) (queryResult.getData().length() / 1024 / 1024); LOGGER.debug(String.format("query result %d has length %d bytes", i, mbSize)); i++; } } finally { if (storage != null) { storage.shutdown(); } } }
From source file:utilities.PopulateDatabase.java
private static void initialise(EntityManagerFactory entityManagerFactory, EntityManager entityManager) throws Throwable { final String urlProperty = "hibernate.connection.url"; final String dialectProperty = "hibernate.dialect"; final List<String> statements; Session session;/* ww w .j ava2 s . c o m*/ String databaseUrl; String databaseName; String databaseDialect; databaseUrl = findProperty(entityManagerFactory, urlProperty); databaseName = StringUtils.substringAfterLast(databaseUrl, "/"); databaseDialect = findProperty(entityManagerFactory, dialectProperty); System.out.println(String.format("Persistence unit: `%s'", PersistenceUnit)); System.out.println(String.format("Database: `%s' (%s)", databaseName, databaseDialect)); System.out.println(); statements = buildSchema(databaseName, databaseDialect); session = entityManager.unwrap(Session.class); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement statement; statement = connection.createStatement(); for (String line : statements) { statement.execute(line); } } }); }