javax.persistence.EntityManagerFactory Java Examples

The following examples show how to use javax.persistence.EntityManagerFactory. 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 check out the related API usage on the sidebar.
Example #1
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void updateItemDescriptions(final EntityManagerFactory emf, String[] newValues, Counts expected) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    final Item i1 = em.find(Item.class, 1L);
    i1.setDescription(newValues[0]);
    final Item i2 = em.find(Item.class, 2L);
    i2.setDescription(newValues[1]);
    final Item i3 = em.find(Item.class, 3L);
    i3.setDescription(newValues[2]);

    transaction.commit();
    em.close();

    assertRegionStats(expected, Item.class.getName(), stats);
}
 
Example #2
Source File: MockJpaInjectionServices.java    From weld-junit with Apache License 2.0 6 votes vote down vote up
@Override
public ResourceReferenceFactory<EntityManagerFactory> registerPersistenceUnitInjectionPoint(InjectionPoint injectionPoint) {
    return new ResourceReferenceFactory<EntityManagerFactory>() {
        @Override
        public ResourceReference<EntityManagerFactory> createResource() {
            if (persistenceUnitFactory == null) {
                throw new IllegalStateException("Persistent unit factory not set, cannot resolve injection point: " + injectionPoint);
            }
            Object unit = persistenceUnitFactory.apply(injectionPoint);
            if (unit == null || unit instanceof EntityManagerFactory) {
                return new SimpleResourceReference<EntityManagerFactory>((EntityManagerFactory) unit);
            }
            throw new IllegalStateException("Not an EntityManagerFactory instance: " + unit);
        }
    };
}
 
Example #3
Source File: JPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void verifyHqlFetch(EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    try {
        EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();

            em.createQuery("from Person p left join fetch p.address a").getResultList();

            transaction.commit();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        }
    } finally {
        em.close();
    }
}
 
Example #4
Source File: PersistenceAnnotationBeanPostProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return a specified persistence unit for the given unit name,
 * as defined through the "persistenceUnits" map.
 * @param unitName the name of the persistence unit
 * @return the corresponding EntityManagerFactory,
 * or {@code null} if none found
 * @see #setPersistenceUnits
 */
protected EntityManagerFactory getPersistenceUnit(String unitName) {
	if (this.persistenceUnits != null) {
		String unitNameForLookup = (unitName != null ? unitName : "");
		if ("".equals(unitNameForLookup)) {
			unitNameForLookup = this.defaultPersistenceUnitName;
		}
		String jndiName = this.persistenceUnits.get(unitNameForLookup);
		if (jndiName == null && "".equals(unitNameForLookup) && this.persistenceUnits.size() == 1) {
			jndiName = this.persistenceUnits.values().iterator().next();
		}
		if (jndiName != null) {
			try {
				return lookup(jndiName, EntityManagerFactory.class);
			}
			catch (Exception ex) {
				throw new IllegalStateException("Could not obtain EntityManagerFactory [" + jndiName + "] from JNDI", ex);
			}
		}
	}
	return null;
}
 
Example #5
Source File: JpaMigrator.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**<p>Executes the database migration for the provided JIRAs numbers.
 * For example, for the https://issues.apache.org/jira/browse/IMAP-165 JIRA, simply invoke
 * with IMAP165 as parameter.
 * You can also invoke with many JIRA at once. They will be all serially executed.</p>
 * 
 * TODO Extract the SQL in JAVA classes to XML file.
 * 
 * @param jiras the JIRAs numbers
 * @throws JpaMigrateException 
 */
public static void main(String[] jiras) throws JpaMigrateException {

    try {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("JamesMigrator");
        EntityManager em = factory.createEntityManager();

        for (String jira: jiras) {
            JpaMigrateCommand jiraJpaMigratable = (JpaMigrateCommand) Class.forName(JPA_MIGRATION_COMMAND_PACKAGE + "." + jira.toUpperCase(Locale.US) + JpaMigrateCommand.class.getSimpleName()).newInstance();
            LOGGER.info("Now executing {} migration", jira);
            em.getTransaction().begin();
            jiraJpaMigratable.migrate(em);
            em.getTransaction().commit();
            LOGGER.info("{} migration is successfully achieved", jira);
        }
    } catch (Throwable t) {
        throw new JpaMigrateException(t);
    }
    
}
 
Example #6
Source File: OpenEntityManagerInViewFilter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Look up the EntityManagerFactory that this filter should use.
 * <p>The default implementation looks for a bean with the specified name
 * in Spring's root application context.
 * @return the EntityManagerFactory to use
 * @see #getEntityManagerFactoryBeanName
 */
protected EntityManagerFactory lookupEntityManagerFactory() {
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
	String emfBeanName = getEntityManagerFactoryBeanName();
	String puName = getPersistenceUnitName();
	if (StringUtils.hasLength(emfBeanName)) {
		return wac.getBean(emfBeanName, EntityManagerFactory.class);
	}
	else if (!StringUtils.hasLength(puName) && wac.containsBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME)) {
		return wac.getBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME, EntityManagerFactory.class);
	}
	else {
		// Includes fallback search for single EntityManagerFactory bean by type.
		return EntityManagerFactoryUtils.findEntityManagerFactory(wac, puName);
	}
}
 
Example #7
Source File: MonitorDataServiceTest.java    From peer-os with Apache License 2.0 6 votes vote down vote up
private void throwDbException() throws SQLException
{
    EntityManagerFactory emf = mock( EntityManagerFactory.class );
    EntityManager em = mock( EntityManager.class );
    EntityManager em1 = mock( EntityManager.class );
    EntityTransaction transaction = mock( EntityTransaction.class );
    when( transaction.isActive() ).thenReturn( false );
    when( em.getTransaction() ).thenThrow( new PersistenceException() ).thenReturn( transaction );
    when( emf.createEntityManager() ).thenReturn( em1 ).thenReturn( em );
    try
    {
        monitorDao = new MonitorDataServiceExt( emf );
    }
    catch ( DaoException e )
    {
        e.printStackTrace();
    }
}
 
Example #8
Source File: EntityManagerFactoryProxy.java    From HotswapAgent with GNU General Public License v2.0 6 votes vote down vote up
private void buildFreshEntityManagerFactory() {
    try {
        Class ejb3ConfigurationClazz = loadClass("org.hibernate.ejb.Ejb3Configuration");
        LOGGER.trace("new Ejb3Configuration()");
        Object cfg = ejb3ConfigurationClazz.newInstance();

        LOGGER.trace("cfg.configure( info, properties );");

        if (info != null) {
            ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "configure",
                    new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);
        }
        else {
            ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "configure",
                    new Class[]{String.class, Map.class}, persistenceUnitName, properties);
        }

        LOGGER.trace("configured.buildEntityManagerFactory()");
        currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "buildEntityManagerFactory",
                new Class[]{});


    } catch (Exception e) {
        LOGGER.error("Unable to build fresh entity manager factory for persistence unit {}", persistenceUnitName);
    }
}
 
Example #9
Source File: OrderConfig.java    From tutorials with MIT License 6 votes vote down vote up
@Bean
public EntityManagerFactory orderEntityManager() {
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("com.baeldung.atomikos.spring.jpa.order");
    factory.setDataSource(orderDataSource());
    Properties jpaProperties = new Properties();
    //jpaProperties.put("hibernate.show_sql", "true");
    //jpaProperties.put("hibernate.format_sql", "true");
    jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect");
    jpaProperties.put("hibernate.current_session_context_class", "jta");
    jpaProperties.put("javax.persistence.transactionType", "jta");
    jpaProperties.put("hibernate.transaction.manager_lookup_class", "com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup");
    jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop");
    factory.setJpaProperties(jpaProperties);
    factory.afterPropertiesSet();
    return factory.getObject();
}
 
Example #10
Source File: SharedEntityManagerBean.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public final void afterPropertiesSet() {
	EntityManagerFactory emf = getEntityManagerFactory();
	if (emf == null) {
		throw new IllegalArgumentException("'entityManagerFactory' or 'persistenceUnitName' is required");
	}
	if (emf instanceof EntityManagerFactoryInfo) {
		EntityManagerFactoryInfo emfInfo = (EntityManagerFactoryInfo) emf;
		if (this.entityManagerInterface == null) {
			this.entityManagerInterface = emfInfo.getEntityManagerInterface();
			if (this.entityManagerInterface == null) {
				this.entityManagerInterface = EntityManager.class;
			}
		}
	}
	else {
		if (this.entityManagerInterface == null) {
			this.entityManagerInterface = EntityManager.class;
		}
	}
	this.shared = SharedEntityManagerCreator.createSharedEntityManager(
			emf, getJpaPropertyMap(), this.synchronizedWithTransaction, this.entityManagerInterface);
}
 
Example #11
Source File: JpaModule.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor used on server side.
 */
private JpaModule(EntityManagerFactory emFactory, EntityManager em, TransactionRunner transactionRunner) {
	this();

	this.emFactory = emFactory;
	this.em = em;
	this.transactionRunner = transactionRunner;
	setQueryFactory(JpaCriteriaQueryFactory.newInstance());

	if (emFactory != null) {
		Set<ManagedType<?>> managedTypes = emFactory.getMetamodel().getManagedTypes();
		for (ManagedType<?> managedType : managedTypes) {
			Class<?> managedJavaType = managedType.getJavaType();
			MetaElement meta = jpaMetaLookup.getMeta(managedJavaType, MetaJpaDataObject.class);
			if (meta instanceof MetaEntity) {
				addRepository(JpaRepositoryConfig.builder(managedJavaType).build());
			}
		}
	}
	this.setRepositoryFactory(new DefaultJpaRepositoryFactory());
}
 
Example #12
Source File: AbstractTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
protected EntityManagerFactory newEntityManagerFactory() {
    PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
    Map configuration = properties();
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        configuration.put(AvailableSettings.INTERCEPTOR, interceptor);
    }
    Integrator integrator = integrator();
    if (integrator != null) {
        configuration.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(integrator));
    }

    EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl(
        new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration
    );
    return entityManagerFactoryBuilder.build();
}
 
Example #13
Source File: LocalContainerEntityManagerFactoryBeanTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testApplicationManagedEntityManagerWithoutTransaction() throws Exception {
	Object testEntity = new Object();
	EntityManager mockEm = mock(EntityManager.class);

	given(mockEmf.createEntityManager()).willReturn(mockEm);

	LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
	EntityManagerFactory emf = cefb.getObject();
	assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());

	assertNotSame("EMF must be proxied", mockEmf, emf);
	EntityManager em = emf.createEntityManager();
	assertFalse(em.contains(testEntity));

	cefb.destroy();

	verify(mockEmf).close();
}
 
Example #14
Source File: JPAEntityManagerFactory.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
public static EntityManagerFactory getEntityManagerFactory(final String pUnit) {
  if (pUnit == null) {
    return null;
  }
  if (emfMap == null) {
    emfMap = new HashMap<String, EntityManagerFactory>();
  }

  if (emfMap.containsKey(pUnit)) {
    return emfMap.get(pUnit);
  } else {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(pUnit);
    emfMap.put(pUnit, emf);
    return emf;
  }

}
 
Example #15
Source File: Migrate.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public void migrate3() {
	Map<String, String> properties = new HashMap<String, String>();
	properties.put(PersistenceUnitProperties.JDBC_PASSWORD, Site.DATABASEPASSWORD);
	properties.put(PersistenceUnitProperties.LOGGING_LEVEL, "fine");
	EntityManagerFactory factory = Persistence.createEntityManagerFactory("botlibre", properties);
	EntityManager em = factory.createEntityManager();
	em.getTransaction().begin();
	try {
		em.createNativeQuery("Update ChatChannel set creator_userid = (Select t2.admins_userid from CHAT_ADMINS t2 where t2.chatchannel_id = id)").executeUpdate();
		em.createNativeQuery("Update Forum set creator_userid = (Select t2.admins_userid from forum_ADMINS t2 where t2.forum_id = id)").executeUpdate();
		em.createNativeQuery("Update BotInstance set creator_userid = (Select t2.admins_userid from PANODRAINSTANCE_ADMINS t2 where t2.instances_id = id)").executeUpdate();
		em.getTransaction().commit();
	} catch (Exception exception) {
		exception.printStackTrace();
	} finally {
		if (em.getTransaction().isActive()) {
			em.getTransaction().rollback();
		}
		em.close();
		factory.close();
	}
}
 
Example #16
Source File: DaoConfig.java    From careconnect-reference-implementation with Apache License 2.0 6 votes vote down vote up
@Bean
public EntityManagerFactory entityManagerFactory() {
    //  final Database database = Database.valueOf(vendor.toUpperCase());

    final LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setPersistenceUnitName("CCRI_PERSISTENCE_UNIT");
    // factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("uk.nhs.careconnect.ri.database.entity");
    factory.setDataSource(dataSource());
    factory.setPersistenceProvider(new HibernatePersistenceProvider());
    factory.setJpaProperties(jpaProperties());
    factory.afterPropertiesSet();


    return factory.getObject();
}
 
Example #17
Source File: PersistenceUtils.java    From kumuluzee with MIT License 6 votes vote down vote up
public static TransactionType getEntityManagerFactoryTransactionType(EntityManagerFactory emf) {

        EntityManager manager = emf.createEntityManager();

        // Hibernate does not throw exception when getTransaction() in JTA context is called, this is the workaround
        // for JTA detection
        if (emf.getProperties().containsKey("hibernate.transaction.coordinator_class") &&
                emf.getProperties().get("hibernate.transaction.coordinator_class") instanceof Class &&
                ((Class) emf.getProperties().get("hibernate.transaction.coordinator_class")).getSimpleName()
                        .equals("JtaTransactionCoordinatorBuilderImpl")) {
            return TransactionType.JTA;
        }

        try {
            manager.getTransaction();

            return TransactionType.RESOURCE_LOCAL;
        } catch (IllegalStateException e) {

            manager.close();
            return TransactionType.JTA;
        }
    }
 
Example #18
Source File: EntityManagerFactoryUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prepare a transaction on the given EntityManager, if possible.
 * @param transactionData arbitrary object that holds transaction data, if any
 * (as returned by prepareTransaction)
 * @param emf the EntityManagerFactory that the EntityManager has been created with
 * @see JpaDialect#cleanupTransaction
 */
private static void cleanupTransaction(Object transactionData, EntityManagerFactory emf) {
	if (emf instanceof EntityManagerFactoryInfo) {
		EntityManagerFactoryInfo emfInfo = (EntityManagerFactoryInfo) emf;
		JpaDialect jpaDialect = emfInfo.getJpaDialect();
		if (jpaDialect != null) {
			jpaDialect.cleanupTransaction(transactionData);
		}
	}
}
 
Example #19
Source File: EncCmpBean.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void lookupPersistenceUnit() throws TestFailureException {
    try {
        try {
            final InitialContext ctx = new InitialContext();
            Assert.assertNotNull("The InitialContext is null", ctx);
            final EntityManagerFactory emf = (EntityManagerFactory) ctx.lookup("java:comp/env/persistence/TestUnit");
            Assert.assertNotNull("The EntityManagerFactory is null", emf);

        } catch (final Exception e) {
            Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage());
        }
    } catch (final AssertionFailedError afe) {
        throw new TestFailureException(afe);
    }
}
 
Example #20
Source File: TestPersistence.java    From development with Apache License 2.0 5 votes vote down vote up
public EntityManagerFactory getEntityManagerFactory(String unitName)
        throws Exception {
    final ITestDB testDb = TestDataSources.get(unitName, runOnProductiveDB);
    if (!initializedDBs.contains(testDb) && !runOnProductiveDB) {
        testDb.initialize();
        initializedDBs.add(testDb);
    }

    EntityManagerFactory f = factoryCache.get(unitName);
    if (f == null) {
        f = buildEntityManagerFactory(testDb, unitName);
        factoryCache.put(unitName, f);
    }
    return f;
}
 
Example #21
Source File: EntityManagerFactoryProducer.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
public EntityManagerFactory produceEntityManagerFactory() {
    Map<String, Object> props = new HashMap<>();
    props.put("javax.persistence.bean.manager", beanManager);
    props.put(Environment.CONNECTION_PROVIDER, TransactionalConnectionProvider.class);
    return Persistence.createEntityManagerFactory(
            "myPu",
            props
    );
}
 
Example #22
Source File: HibernateJpaSessionFactoryBean.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public SessionFactory getObject() {
	EntityManagerFactory emf = getEntityManagerFactory();
	Assert.state(emf != null, "EntityManagerFactory must not be null");
	try {
		Method getSessionFactory = emf.getClass().getMethod("getSessionFactory");
		return (SessionFactory) ReflectionUtils.invokeMethod(getSessionFactory, emf);
	}
	catch (NoSuchMethodException ex) {
		throw new IllegalStateException("No compatible Hibernate EntityManagerFactory found: " + ex);
	}
}
 
Example #23
Source File: JPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void storeTestPersons(final EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    persistNewPerson(em, "Gizmo");
    persistNewPerson(em, "Quarkus");
    persistNewPerson(em, "Hibernate ORM");
    transaction.commit();
    em.close();
}
 
Example #24
Source File: StatefulContainer.java    From tomee with Apache License 2.0 5 votes vote down vote up
private Index<EntityManagerFactory, JtaEntityManagerRegistry.EntityManagerTracker> createEntityManagers(final BeanContext beanContext) {
    // create the extended entity managers
    final Index<EntityManagerFactory, BeanContext.EntityManagerConfiguration> factories = beanContext.getExtendedEntityManagerFactories();
    Index<EntityManagerFactory, JtaEntityManagerRegistry.EntityManagerTracker> entityManagers = null;
    if (factories != null && factories.size() > 0) {
        entityManagers = new Index<>(new ArrayList<>(factories.keySet()));
        for (final Map.Entry<EntityManagerFactory, BeanContext.EntityManagerConfiguration> entry : factories.entrySet()) {
            final EntityManagerFactory entityManagerFactory = entry.getKey();

            JtaEntityManagerRegistry.EntityManagerTracker entityManagerTracker = entityManagerRegistry.getInheritedEntityManager(entityManagerFactory);
            final EntityManager entityManager;
            if (entityManagerTracker == null) {
                final Map properties = entry.getValue().getProperties();
                final SynchronizationType synchronizationType = entry.getValue().getSynchronizationType();
                if (synchronizationType != null) {
                    if (properties != null) {
                        entityManager = entityManagerFactory.createEntityManager(synchronizationType, properties);
                    } else {
                        entityManager = entityManagerFactory.createEntityManager(synchronizationType);
                    }
                } else if (properties != null) {
                    entityManager = entityManagerFactory.createEntityManager(properties);
                } else {
                    entityManager = entityManagerFactory.createEntityManager();
                }
                entityManagerTracker = new JtaEntityManagerRegistry.EntityManagerTracker(entityManager, synchronizationType != SynchronizationType.UNSYNCHRONIZED);
            } else {
                entityManagerTracker.incCounter();
            }
            entityManagers.put(entityManagerFactory, entityManagerTracker);
        }
    }
    return entityManagers;
}
 
Example #25
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void testQuery(EntityManagerFactory entityManagerFactory) {
    //Load all persons and run some checks on the query results:
    Map<String, Counts> counts = new TreeMap<>();
    counts.put(Person.class.getName(), new Counts(4, 0, 0, 4));
    counts.put(RegionFactory.DEFAULT_QUERY_RESULTS_REGION_UNQUALIFIED_NAME, new Counts(1, 0, 1, 1));
    verifyListOfExistingPersons(entityManagerFactory, counts);

    //Load all persons with same query and verify query results
    counts = new TreeMap<>();
    counts.put(Person.class.getName(), new Counts(0, 4, 0, 4));
    counts.put(RegionFactory.DEFAULT_QUERY_RESULTS_REGION_UNQUALIFIED_NAME, new Counts(0, 1, 0, 1));
    verifyListOfExistingPersons(entityManagerFactory, counts);
}
 
Example #26
Source File: KradEclipseLinkCustomizerTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testSequences_AnnotationAtMethodLevel() throws Exception {
    EntityManagerFactory factory = (EntityManagerFactory) context.getBean("entityManagerFactory");
    assertNotNull(factory);

    TestEntity3 testEntity1 = new TestEntity3();
    testEntity1.setName("MyAwesomeTestEntity1");

    // number in this case is generated from a sequence
    assertNull(testEntity1.getNumber());

    EntityManager entityManager = factory.createEntityManager();
    try {
        entityManager.persist(testEntity1);
        assertNotNull(testEntity1.getNumber());
    } finally {
        entityManager.close();
    }

    TestEntity3 testEntity2 = new TestEntity3();
    testEntity2.setName("MyAwesomeTestEntity2");

    assertNull(testEntity2.getNumber());

    entityManager = factory.createEntityManager();
    try {
        // try merge here and make sure it works with that as well
        testEntity2 = entityManager.merge(testEntity2);
        assertNotNull(testEntity2.getNumber());
        assertEquals(Integer.valueOf(Integer.valueOf(testEntity1.getNumber()).intValue() + 1), Integer.valueOf(
                testEntity2.getNumber()));
    } finally {
        entityManager.close();
    }

}
 
Example #27
Source File: DefaultIdManager.java    From onedev with MIT License 5 votes vote down vote up
@Sessional
@Override
public void init() {
	for (EntityType<?> entityType: ((EntityManagerFactory)persistManager.getSessionFactory()).getMetamodel().getEntities()) {
		Class<?> entityClass = entityType.getJavaType();
		nextIds.put(entityClass, new AtomicLong(getMaxId(entityClass)+1));
	}
}
 
Example #28
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void testDeleteViaRemove(final EntityManagerFactory emf) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();
    em.remove(em.find(Pokemon.class, 3));
    em.remove(em.find(Pokemon.class, 248));
    em.remove(em.find(Pokemon.class, 242));
    transaction.commit();
    em.close();

    assertRegionStats(new Counts(0, 3, 0, 4), Pokemon.class.getName(), stats);

    stats = getStatistics(emf);

    em = emf.createEntityManager();
    transaction = em.getTransaction();
    transaction.begin();
    if (em.find(Pokemon.class, 3) != null
            || em.find(Pokemon.class, 248) != null
            || em.find(Pokemon.class, 242) != null) {
        throw new RuntimeException("Pokemons should have been deleted");
    }

    transaction.commit();
    em.close();

    assertRegionStats(new Counts(0, 0, 3, 4), Pokemon.class.getName(), stats);
}
 
Example #29
Source File: ReactivePersistenceProvider.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p/>
 * Note: per-spec, the values passed as {@code properties} override values found in {@link PersistenceUnitInfo}
 */
@Override
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
	log.tracef( "Starting createContainerEntityManagerFactory : %s", info.getPersistenceUnitName() );

	return getEntityManagerFactoryBuilder( info, properties ).build();
}
 
Example #30
Source File: FullHistoryTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Deployment(resources = { "org/activiti/standalone/jpa/JPAVariableTest.testQueryJPAVariable.bpmn20.xml" })
public void testReadJpaVariableValueFromHistoricVariableUpdate() {
    org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl activiti5ProcessEngineConfig = (org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl) processEngineConfiguration.getFlowable5CompatibilityHandler()
            .getRawProcessConfiguration();

    EntityManagerSessionFactory entityManagerSessionFactory = (EntityManagerSessionFactory) activiti5ProcessEngineConfig
            .getSessionFactories()
            .get(EntityManagerSession.class);

    EntityManagerFactory entityManagerFactory = entityManagerSessionFactory.getEntityManagerFactory();

    String executionId = runtimeService.startProcessInstanceByKey("JPAVariableProcess").getProcessInstanceId();
    String variableName = "name";

    FieldAccessJPAEntity entity = new FieldAccessJPAEntity();
    entity.setId(1L);
    entity.setValue("Test");

    EntityManager manager = entityManagerFactory.createEntityManager();
    manager.getTransaction().begin();
    manager.persist(entity);
    manager.flush();
    manager.getTransaction().commit();
    manager.close();

    org.flowable.task.api.Task task = taskService.createTaskQuery().processInstanceId(executionId).taskName("my task").singleResult();

    runtimeService.setVariable(executionId, variableName, entity);
    taskService.complete(task.getId());

    List<org.activiti.engine.history.HistoricDetail> variableUpdates = activiti5ProcessEngineConfig.getHistoryService().createHistoricDetailQuery().processInstanceId(executionId).variableUpdates().list();

    assertEquals(1, variableUpdates.size());
    org.activiti.engine.history.HistoricVariableUpdate update = (org.activiti.engine.history.HistoricVariableUpdate) variableUpdates.get(0);
    assertNotNull(update.getValue());
    assertTrue(update.getValue() instanceof FieldAccessJPAEntity);

    assertEquals(entity.getId(), ((FieldAccessJPAEntity) update.getValue()).getId());
}