Java Code Examples for javax.persistence.spi.PersistenceUnitInfo

The following examples show how to use javax.persistence.spi.PersistenceUnitInfo. 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
@Test
public void testExample5() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example5.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement5", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getMappingFileNames().size());
	assertEquals("order1.xml", info[0].getMappingFileNames().get(0));
	assertEquals("order2.xml", info[0].getMappingFileNames().get(1));

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertEquals("com.acme.AcmePersistence", info[0].getPersistenceProviderClassName());
	assertEquals(0, info[0].getProperties().keySet().size());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 2
Source Project: spring-analysis-note   Source File: PersistenceXmlParsingTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testMetaInfCase() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/META-INF/persistence.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 3
Source Project: spring-analysis-note   Source File: PersistenceXmlParsingTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testExample2() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example2.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);

	assertEquals("OrderManagement2", info[0].getPersistenceUnitName());

	assertEquals(1, info[0].getMappingFileNames().size());
	assertEquals("mappings.xml", info[0].getMappingFileNames().get(0));
	assertEquals(0, info[0].getProperties().keySet().size());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 4
Source Project: openwebbeans-meecrowave   Source File: EntityManagerBean.java    License: Apache License 2.0 6 votes vote down vote up
void init(final PersistenceUnitInfo info, final BeanManager bm) {
    final PersistenceProvider provider;
    try {
        provider = PersistenceProvider.class.cast(
                Thread.currentThread().getContextClassLoader().loadClass(info.getPersistenceProviderClassName()).newInstance());
    } catch (final InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        throw new IllegalArgumentException("Bad provider: " + info.getPersistenceProviderClassName());
    }
    final EntityManagerFactory factory = provider.createContainerEntityManagerFactory(info, new HashMap() {{
        put("javax.persistence.bean.manager", bm);
        if (ValidationMode.NONE != info.getValidationMode()) {
            ofNullable(findValidatorFactory(bm)).ifPresent(factory -> put("javax.persistence.validation.factory", factory));
        }
    }});
    instanceFactory = synchronization == SynchronizationType.SYNCHRONIZED ? factory::createEntityManager : () -> factory.createEntityManager(synchronization);
}
 
Example 5
Source Project: spring-analysis-note   Source File: PersistenceXmlParsingTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testExample5() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example5.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement5", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getMappingFileNames().size());
	assertEquals("order1.xml", info[0].getMappingFileNames().get(0));
	assertEquals("order2.xml", info[0].getMappingFileNames().get(1));

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertEquals("com.acme.AcmePersistence", info[0].getPersistenceProviderClassName());
	assertEquals(0, info[0].getProperties().keySet().size());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 6
/**
 * Creates the container entity manager factory proxy.
 *
 * @param info            persistent unit definition
 * @param properties            properties to create entity manager factory
 * @param original            entity manager factory
 * @return proxy of entity manager
 */
public static EntityManagerFactory createContainerEntityManagerFactoryProxy(PersistenceUnitInfo info,
        Map<?,?> properties, EntityManagerFactory original) {
    // ensure only once
    if (wrappedPersistenceUnitNames.contains(info.getPersistenceUnitName())){
        return original;
    }
    wrappedPersistenceUnitNames.add(info.getPersistenceUnitName());

    EntityManagerFactoryProxy wrapper = EntityManagerFactoryProxy.getWrapper(info.getPersistenceUnitName());
    EntityManagerFactory proxy = wrapper.proxy(original, info.getPersistenceUnitName(), info, properties);

    initPlugin(original);

    LOGGER.debug("Returning container EntityManager proxy {} instead of EntityManager {}", proxy.getClass(),
            original);
    return proxy;
}
 
Example 7
Source Project: javamelody   Source File: JpaPersistence.java    License: Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public EntityManagerFactory createContainerEntityManagerFactory(final PersistenceUnitInfo info,
		final Map map) {
	initJpaCounter();
	final PersistenceProvider persistenceProvider = findDelegate(map);
	// on surcharge PersistenceUnitInfo.getPersistenceProviderClassName()
	// pour retourner le PersistenceProvider délégué et pas nous même
	final PersistenceUnitInfo proxiedInfo = createPersistentUnitInfoProxy(info,
			persistenceProvider);
	final Map overridenMap = new HashMap();
	if (map != null) {
		overridenMap.putAll(map);
	}
	// #869 No Persistence provider for EntityManager, with Hibernate 5.4 & JPA
	// (when JpaOverridePersistenceXmlClassLoader is not enough)
	overridenMap.put(JPA_PERSISTENCE_PROVIDER, persistenceProvider.getClass().getName());
	final EntityManagerFactory entityManagerFactory = persistenceProvider
			.createContainerEntityManagerFactory(proxiedInfo, overridenMap);
	if (entityManagerFactory == null) {
		return null;
	}
	return JpaWrapper.createEntityManagerFactoryProxy(entityManagerFactory);
}
 
Example 8
@Override
public PersistenceUnitInfo obtainDefaultPersistenceUnitInfo() {
	if (this.persistenceUnitInfoNames.isEmpty()) {
		throw new IllegalStateException("No persistence units parsed from " +
				ObjectUtils.nullSafeToString(this.persistenceXmlLocations));
	}
	if (this.persistenceUnitInfos.isEmpty()) {
		throw new IllegalStateException("All persistence units from " +
				ObjectUtils.nullSafeToString(this.persistenceXmlLocations) + " already obtained");
	}
	if (this.persistenceUnitInfos.size() > 1 && this.defaultPersistenceUnitName != null) {
		return obtainPersistenceUnitInfo(this.defaultPersistenceUnitName);
	}
	PersistenceUnitInfo pui = this.persistenceUnitInfos.values().iterator().next();
	this.persistenceUnitInfos.clear();
	return pui;
}
 
Example 9
@Override
public PersistenceUnitInfo obtainDefaultPersistenceUnitInfo() {
	if (this.persistenceUnitInfoNames.isEmpty()) {
		throw new IllegalStateException("No persistence units parsed from " +
				ObjectUtils.nullSafeToString(this.persistenceXmlLocations));
	}
	if (this.persistenceUnitInfos.isEmpty()) {
		throw new IllegalStateException("All persistence units from " +
				ObjectUtils.nullSafeToString(this.persistenceXmlLocations) + " already obtained");
	}
	if (this.persistenceUnitInfos.size() > 1) {
		return obtainPersistenceUnitInfo(this.defaultPersistenceUnitName);
	}
	PersistenceUnitInfo pui = this.persistenceUnitInfos.values().iterator().next();
	this.persistenceUnitInfos.clear();
	return pui;
}
 
Example 10
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 11
Source Project: java-technology-stack   Source File: PersistenceXmlParsingTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testExample2() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example2.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);

	assertEquals("OrderManagement2", info[0].getPersistenceUnitName());

	assertEquals(1, info[0].getMappingFileNames().size());
	assertEquals("mappings.xml", info[0].getMappingFileNames().get(0));
	assertEquals(0, info[0].getProperties().keySet().size());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 12
Source Project: java-technology-stack   Source File: PersistenceXmlParsingTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testExample3() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example3.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement3", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertEquals(0, info[0].getProperties().keySet().size());
	assertNull(info[0].getJtaDataSource());
	assertNull(info[0].getNonJtaDataSource());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 13
@Test
public void testExample2() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example2.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);

	assertEquals("OrderManagement2", info[0].getPersistenceUnitName());

	assertEquals(1, info[0].getMappingFileNames().size());
	assertEquals("mappings.xml", info[0].getMappingFileNames().get(0));
	assertEquals(0, info[0].getProperties().keySet().size());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 14
@Before
public void init() {
    PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());

    Map<String, Object> configuration = new HashMap<>();

    Integrator integrator = integrator();
    if (integrator != null) {
        configuration.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(integrator));
    }

    emf = new HibernatePersistenceProvider().createContainerEntityManagerFactory(
        persistenceUnitInfo,
        configuration
    );
}
 
Example 15
@SuppressWarnings("rawtypes")
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
	Ejb3Configuration cfg = new Ejb3Configuration();
	if (info instanceof SmartPersistenceUnitInfo) {
		for (String managedPackage : ((SmartPersistenceUnitInfo) info).getManagedPackages()) {
			cfg.addPackage(managedPackage);
		}
	}
	Ejb3Configuration configured = cfg.configure(info, properties);
	return (configured != null ? configured.buildEntityManagerFactory() : null);
}
 
Example 16
Source Project: quickperf   Source File: SqlTestBaseJUnit5.java    License: Apache License 2.0 5 votes vote down vote up
private PersistenceUnitInfo buildPersistenceUnitInfo() {
    DataSource baseDataSource = TestDataSourceBuilder.aDataSource().build();
    ProxyDataSource proxyDataSource = aDataSourceBuilder()
                                      .buildProxy(baseDataSource);
    Properties hibernateProperties = HibernateConfigBuilder.anHibernateConfig().build();
    return PersistenceUnitInfoBuilder.aPersistenceUnitInfo()
                                     .build(   proxyDataSource
                                             , hibernateProperties
                                             , Book.class);
}
 
Example 17
/**
 * Called after the EntityManagerFactory is initialized and processed.  Delegates to the data populator
 * any insertion of data into the DataSource
 *
 * @param emf the newly created EntityManagerFactory
 * @param pui the PersistenceUnit that the EntityManagerFactory was initialized for
 */
@Override
protected void postProcessEntityManagerFactory(EntityManagerFactory emf, PersistenceUnitInfo pui) {
    if (populator != null) {
        //Create an entity manager to force initialization of the context and then populate
        emf.createEntityManager().close();
        try {
            populator.initialize(this.getDataSource());
        } catch (RuntimeException e) {
            logger.error("Database population has failed. It will be empty.", e);
        }
    }
    super.postProcessEntityManagerFactory(emf, pui);
}
 
Example 18
Source Project: quickperf   Source File: SqlTestBaseJUnit4.java    License: Apache License 2.0 5 votes vote down vote up
private PersistenceUnitInfo buildPersistenceUnitInfo() {
    DataSource baseDataSource = TestDataSourceBuilder.aDataSource().build();
    ProxyDataSource proxyDataSource = aDataSourceBuilder().buildProxy(baseDataSource);
    Properties hibernateProperties = getHibernateProperties();
    return aPersistenceUnitInfo().build(proxyDataSource
                                      , hibernateProperties
                                      , Book.class);
}
 
Example 19
Source Project: quickperf   Source File: SqlTestBase.java    License: Apache License 2.0 5 votes vote down vote up
private PersistenceUnitInfo buildPersistenceUnitInfo() {
    DataSource baseDataSource = TestDataSourceBuilder.aDataSource().build();
    ProxyDataSource proxyDataSource = aDataSourceBuilder().buildProxy(baseDataSource);
    Properties hibernateProperties = getHibernateProperties();
    return aPersistenceUnitInfo().build(proxyDataSource
                                      , hibernateProperties
                                      , Book.class);
}
 
Example 20
Source Project: hammock   Source File: EntityManagerFactoryProvider.java    License: Apache License 2.0 5 votes vote down vote up
PersistenceUnitInfo getDefaultPersistenceUnitInfo() {
    DataSource dataSource = CDI.current().select(DataSource.class).select(database(defaultDataSourceName)).get();
    List<String> extraClasses = new ArrayList<>();
    if(entityClasses.length() > 0) {
        String[] parts = entityClasses.split(",");
        extraClasses = asList(parts);
    }
    return builder
            .withClasses(jpaExtension.getEntityClasses())
            .withClasses(extraClasses)
            .withDataSource(dataSource)
            .loadAllProperties(createPrefix(DEFAULT_EMF), true)
            .build();
}
 
Example 21
@Override
public PersistenceUnitInfo obtainPersistenceUnitInfo(String persistenceUnitName) {
	PersistenceUnitInfo pui = this.persistenceUnitInfos.remove(persistenceUnitName);
	if (pui == null) {
		if (!this.persistenceUnitInfoNames.contains(persistenceUnitName)) {
			throw new IllegalArgumentException(
					"No persistence unit with name '" + persistenceUnitName + "' found");
		}
		else {
			throw new IllegalStateException(
					"Persistence unit with name '" + persistenceUnitName + "' already obtained");
		}
	}
	return pui;
}
 
Example 22
/**
 * {@inheritDoc}
 */
@Override
public DataSource getDataSource() {
    PersistenceUnitInfo pui = internalFactoryBean.getPersistenceUnitInfo();
    if (internalFactoryBean.getPersistenceUnitInfo() != null) {
        return (pui.getJtaDataSource() != null ?
                pui.getJtaDataSource() :
                pui.getNonJtaDataSource());
    }
    return (persistenceUnitManager.getDefaultJtaDataSource() != null ?
            persistenceUnitManager.getDefaultJtaDataSource() :
            this.persistenceUnitManager.getDefaultDataSource());
}
 
Example 23
@Override
@SuppressWarnings("rawtypes")
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
	final List<String> mergedClassesAndPackages = new ArrayList<String>(info.getManagedClassNames());
	if (info instanceof SmartPersistenceUnitInfo) {
		mergedClassesAndPackages.addAll(((SmartPersistenceUnitInfo) info).getManagedPackages());
	}
	return new EntityManagerFactoryBuilderImpl(
			new PersistenceUnitInfoDescriptor(info) {
				@Override
				public List<String> getManagedClassNames() {
					return mergedClassesAndPackages;
				}
			}, properties).build();
}
 
Example 24
Source Project: spring-analysis-note   Source File: PersistenceXmlParsingTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testExample4() throws Exception {
	SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
	DataSource ds = new DriverManagerDataSource();
	builder.bind("java:comp/env/jdbc/MyDB", ds);

	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example4.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement4", info[0].getPersistenceUnitName());

	assertEquals(1, info[0].getMappingFileNames().size());
	assertEquals("order-mappings.xml", info[0].getMappingFileNames().get(0));

	assertEquals(3, info[0].getManagedClassNames().size());
	assertEquals("com.acme.Order", info[0].getManagedClassNames().get(0));
	assertEquals("com.acme.Customer", info[0].getManagedClassNames().get(1));
	assertEquals("com.acme.Item", info[0].getManagedClassNames().get(2));

	assertTrue("Exclude unlisted should be true when no value.", info[0].excludeUnlistedClasses());

	assertSame(PersistenceUnitTransactionType.RESOURCE_LOCAL, info[0].getTransactionType());
	assertEquals(0, info[0].getProperties().keySet().size());

	builder.clear();
}
 
Example 25
Source Project: minnal   Source File: JPAPluginTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setup() {
	plugin = spy(new JPAPlugin());
	provider = mock(PersistenceProvider.class);
	persistenceUnitInfo = mock(PersistenceUnitInfo.class);
	application = mock(Application.class);
	ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
	when(configuration.getName()).thenReturn("test");
	when(configuration.getDatabaseConfiguration()).thenReturn(mock(DatabaseConfiguration.class));
	when(application.getConfiguration()).thenReturn(configuration);
	
	doReturn(persistenceUnitInfo).when(plugin).createPersistenceUnitInfo(configuration, provider);
	doReturn(Arrays.asList(provider)).when(plugin).getProviders();
}
 
Example 26
Source Project: spring-analysis-note   Source File: PersistenceXmlParsingTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testJpa1ExcludeUnlisted() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-exclude-1.0.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals("The number of persistence units is incorrect.", 4, info.length);

	PersistenceUnitInfo noExclude = info[0];
	assertNotNull("noExclude should not be null.", noExclude);
	assertEquals("noExclude name is not correct.", "NoExcludeElement", noExclude.getPersistenceUnitName());
	assertFalse("Exclude unlisted should default false in 1.0.", noExclude.excludeUnlistedClasses());

	PersistenceUnitInfo emptyExclude = info[1];
	assertNotNull("emptyExclude should not be null.", emptyExclude);
	assertEquals("emptyExclude name is not correct.", "EmptyExcludeElement", emptyExclude.getPersistenceUnitName());
	assertTrue("emptyExclude should be true.", emptyExclude.excludeUnlistedClasses());

	PersistenceUnitInfo trueExclude = info[2];
	assertNotNull("trueExclude should not be null.", trueExclude);
	assertEquals("trueExclude name is not correct.", "TrueExcludeElement", trueExclude.getPersistenceUnitName());
	assertTrue("trueExclude should be true.", trueExclude.excludeUnlistedClasses());

	PersistenceUnitInfo falseExclude = info[3];
	assertNotNull("falseExclude should not be null.", falseExclude);
	assertEquals("falseExclude name is not correct.", "FalseExcludeElement", falseExclude.getPersistenceUnitName());
	assertFalse("falseExclude should be false.", falseExclude.excludeUnlistedClasses());
}
 
Example 27
Source Project: hypersistence-optimizer   Source File: AbstractTest.java    License: Apache License 2.0 5 votes vote down vote up
protected EntityManagerFactory newEntityManagerFactory() {
    PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
    Map<String, Object> configuration = new HashMap<String, Object>();
    configuration.put(AvailableSettings.INTERCEPTOR, interceptor());

    EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl(
        new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration
    );
    return entityManagerFactoryBuilder.build();
}
 
Example 28
Source Project: hammock   Source File: EntityManagerFactoryProvider.java    License: Apache License 2.0 5 votes vote down vote up
public EntityManagerFactory lookupEntityManagerFactory(String name) {
    return entityManagerFactoryMap.computeIfAbsent(name, s -> {
        PersistenceUnitInfo persistenceUnitInfo = jpaExtension.getPersistenceUnitInfo(name);
        if (s.equals(DEFAULT_EMF) && persistenceUnitInfo == null) {
            persistenceUnitInfo = getDefaultPersistenceUnitInfo();
        }
        if (persistenceUnitInfo != null) {
            PersistenceProvider provider = getPersistenceProvider();
            return provider.createContainerEntityManagerFactory(persistenceUnitInfo, emptyMap());
        } else {
            Map<String, String> properties = ConfigLoader.loadAllProperties(createPrefix(s), true);
            return Persistence.createEntityManagerFactory(s, properties);
        }
    });
}
 
Example 29
@Override
public PersistenceUnitInfo obtainPersistenceUnitInfo(String persistenceUnitName) {
	PersistenceUnitInfo pui = this.persistenceUnitInfos.remove(persistenceUnitName);
	if (pui == null) {
		if (!this.persistenceUnitInfoNames.contains(persistenceUnitName)) {
			throw new IllegalArgumentException(
					"No persistence unit with name '" + persistenceUnitName + "' found");
		}
		else {
			throw new IllegalStateException(
					"Persistence unit with name '" + persistenceUnitName + "' already obtained");
		}
	}
	return pui;
}
 
Example 30
/**
 * Builds the fresh entity manager factory.
 */
// from HibernatePersistence.createContainerEntityManagerFactory()
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);
    }
}