类org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager源码实例Demo

下面列出了怎么用org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager的API类实例代码及写法,或者点击链接到github查看源代码。

public void generateSchema() throws MojoFailureException
{
    final Map<String, Object> cfg = buildCfg();
    String[] allBasePackages = this.getBasePackages();
    getLog().info("Using base packages " + StringUtils.arrayToDelimitedString(allBasePackages, ", "));
    final PersistenceProvider provider = new PersistenceProvider();
    final DefaultPersistenceUnitManager manager = new DefaultPersistenceUnitManager();
    manager.setDefaultPersistenceUnitRootLocation(null);
    manager.setDefaultPersistenceUnitName("default");
    manager.setPackagesToScan(allBasePackages);
    final String[] zeroPULocations = new String[]{};
    manager.setPersistenceXmlLocations(zeroPULocations);
    manager.afterPropertiesSet();

    final SmartPersistenceUnitInfo puInfo = (SmartPersistenceUnitInfo) manager.obtainDefaultPersistenceUnitInfo();
    puInfo.setPersistenceProviderPackageName(provider.getClass().getName());
    getLog().info("Entities found : " + puInfo.getManagedClassNames().size());
    getLog().debug("Managed class names:\n    * " + StringUtils.collectionToDelimitedString(puInfo.getManagedClassNames(), "\n    * "));
    puInfo.getProperties().putAll(cfg);
    provider.generateSchema(new DelegatingPuInfo(puInfo), cfg);
}
 
源代码2 项目: spring4-understanding   文件: AbstractJpaTests.java
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
	if (bean instanceof LocalContainerEntityManagerFactoryBean) {
		((LocalContainerEntityManagerFactoryBean) bean).setLoadTimeWeaver(this.ltw);
	}
	if (bean instanceof DefaultPersistenceUnitManager) {
		((DefaultPersistenceUnitManager) bean).setLoadTimeWeaver(this.ltw);
	}
	return bean;
}
 
源代码3 项目: rice   文件: KradEntityManagerFactoryBean.java
/**
 * Creates a persistence unit manager.
 *
 * @return a persistence unit manager.
 */
protected DefaultPersistenceUnitManager createPersistenceUnitManager() {
    DefaultPersistenceUnitManager pum = new DefaultPersistenceUnitManager();
    // IMPORTANT! - setting these to empty String arrays, this triggers the DefaultPersistenceUnitManager to
    // behave appropriately and ignore persistence.xml files from META-INF/persistence.xml as well as allowing for
    // an empty/minimal persistence unit to be created.
    //
    // Note that while Intellij complains about "Redundant array creation for calling varargs method", we really do
    // need to pass an empty array here in order for this code to work properly.
    pum.setPersistenceXmlLocations(new String[0]);
    pum.setMappingResources(new String[0]);
    pum.setPackagesToScan(new String[0]);
    return pum;
}
 
源代码4 项目: lutece-core   文件: JPAStartupService.java
/**
 * Initialize JPA objects (Datasource, Persistence Unit Manager, Entity Manager Factory, Transaction Manager) for each pool.
 */
public void process( )
{
    ReferenceList list = new ReferenceList( );
    AppConnectionService.getPoolList( list );

    Map<String, EntityManagerFactory> mapFactories = new HashMap<>( );
    List<PlatformTransactionManager> listTransactionManagers = new ArrayList<>( );
    _log.info( "JPA Startup Service : Initializing JPA objects ..." );

    String strDialectProperty = AppPropertiesService.getProperty( JPA_DIALECT_PROPERTY );

    for ( ReferenceItem poolItem : list )
    {
        String strPoolname = poolItem.getCode( );

        DataSource ds = AppConnectionService.getPoolManager( ).getDataSource( strPoolname );
        _log.info( "JPA Startup Service : DataSource retrieved for pool : " + strPoolname );
        _log.debug( "> DS : " + ds.toString( ) );

        DefaultPersistenceUnitManager pum = new DefaultPersistenceUnitManager( );
        pum.setDefaultDataSource( ds );

        PersistenceUnitPostProcessor [ ] postProcessors = {
                new JPAPersistenceUnitPostProcessor( )
        };
        pum.setPersistenceUnitPostProcessors( postProcessors );

        pum.afterPropertiesSet( );

        _log.info( "JPA Startup Service : Persistence Unit Manager for pool : " + strPoolname );
        _log.debug( "> PUM : " + pum.toString( ) );

        LocalContainerEntityManagerFactoryBean lcemfb = new LocalContainerEntityManagerFactoryBean( );
        lcemfb.setDataSource( ds );
        lcemfb.setPersistenceUnitManager( pum );
        lcemfb.setPersistenceUnitName( "jpaLuteceUnit" );

        JpaDialect jpaDialect = SpringContextService.getBean( "jpaDialect" );
        lcemfb.setJpaDialect( jpaDialect );

        Map mapJpaProperties = SpringContextService.getBean( "jpaPropertiesMap" );
        lcemfb.setJpaPropertyMap( mapJpaProperties );

        String strDialect = AppPropertiesService.getProperty( poolItem.getName( ) + ".dialect" );

        // replace default dialect if <poolname>.dialect is specified
        if ( StringUtils.isNotBlank( strDialect ) )
        {
            mapJpaProperties.put( strDialectProperty, strDialect );
        }

        _log.debug( "Using dialect " + mapJpaProperties.get( strDialectProperty ) + " for pool " + poolItem.getName( ) );

        JpaVendorAdapter jpaVendorAdapter = SpringContextService.getBean( "jpaVendorAdapter" );
        lcemfb.setJpaVendorAdapter( jpaVendorAdapter );

        lcemfb.afterPropertiesSet( );

        EntityManagerFactory emf = lcemfb.getNativeEntityManagerFactory( );
        _log.info( "JPA Startup Service : EntityManagerFactory created for pool : " + strPoolname );
        _log.debug( "> EMF : " + emf.toString( ) );

        JpaTransactionManager tm = new JpaTransactionManager( );
        tm.setEntityManagerFactory( emf );
        tm.setJpaDialect( jpaDialect );
        _log.debug( "> JpaDialect " + jpaDialect );
        tm.afterPropertiesSet( );
        _log.info( "JPA Startup Service : JPA TransactionManager created for pool : " + strPoolname );
        _log.debug( "> TM : " + tm.toString( ) );

        mapFactories.put( strPoolname, emf );
        listTransactionManagers.add( tm );
    }

    EntityManagerService ems = SpringContextService.getBean( "entityManagerService" );
    ems.setMapFactories( mapFactories );

    ChainedTransactionManager ctm = SpringContextService.getBean( "transactionManager" );
    ctm.setTransactionManagers( listTransactionManagers );
    _log.info( "JPA Startup Service : completed successfully" );
}
 
private void generate() throws Exception {
    Map<String, Object> map = JpaSchemaGeneratorUtils.buildProperties(this);
    if (getVendor() == null) {
        // with persistence.xml
        Persistence.generateSchema(this.persistenceUnitName, map);
    } else {
        PersistenceProvider provider = getProviderClass().newInstance();
        List<String> packages = getPackageToScan();
        if (packages.isEmpty()) {
            throw new IllegalArgumentException("packageToScan is required on xml-less mode.");
        }

        DefaultPersistenceUnitManager manager = new DefaultPersistenceUnitManager();
        manager.setDefaultPersistenceUnitName(getPersistenceUnitName());
        manager.setPackagesToScan(packages.toArray(new String[packages.size()]));
        // issue #22
        Field persistenceXmlLocations = manager.getClass().getDeclaredField("persistenceXmlLocations");
        persistenceXmlLocations.setAccessible(true);
        persistenceXmlLocations.set(manager, new String[0]);
        manager.afterPropertiesSet();

        SmartPersistenceUnitInfo info = (SmartPersistenceUnitInfo) manager.obtainDefaultPersistenceUnitInfo();
        info.setPersistenceProviderPackageName(provider.getClass().getName());
        info.getProperties().putAll(map);

        // Path persistenceXml = null;
        /* @formatter:off */
        // if (Vendor.datanucleus.equals(getVendor())) {
        // // datanucleus must need persistence.xml
        // Path path = Paths.get(project.getBuild().getOutputDirectory(), "META-INF");
        // persistenceXml = Files.createTempFile(path, "persistence-", ".xml");
        // try (BufferedWriter writer = Files.newBufferedWriter(persistenceXml, StandardCharsets.UTF_8)) {
        // PrintWriter out = new PrintWriter(writer);
        // out.println("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
        // out.println("<persistence version=\"2.1\"");
        // out.println(" xmlns=\"http://xmlns.jcp.org/xml/ns/persistence\"
        // xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
        // out.println(" xsi:schemaLocation=\"http://xmlns.jcp.org/xml/ns/persistence
        // http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_1.xsd\">");
        // out.printf(" <persistence-unit name=\"%s\" transaction-type=\"RESOURCE_LOCAL\">\n",
        // info.getPersistenceUnitName());
        // out.println(" <provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>");
        // out.println(" <exclude-unlisted-classes>false</exclude-unlisted-classes>");
        // out.println(" </persistence-unit>");
        // out.println("</persistence>");
        // }
        // map.put(PropertyNames.PROPERTY_PERSISTENCE_XML_FILENAME, persistenceXml.toAbsolutePath().toString());
        // // datanucleus does not support execution order...
        // map.remove(PersistenceUnitProperties.SCHEMA_GENERATION_CREATE_SOURCE);
        // map.remove(PersistenceUnitProperties.SCHEMA_GENERATION_DROP_SOURCE);
        // }
        /* @formatter:on */

        try {
            provider.generateSchema(info, map);
        } finally {
            // if (persistenceXml != null) {
            // Files.delete(persistenceXml);
            // }
        }
    }
}
 
源代码6 项目: rice   文件: KradEntityManagerFactoryBean.java
/**
 * Returns a reference to the internal {@link DefaultPersistenceUnitManager} which is used by this factory bean.
 *
 * @return the internal persistence unit manager, will never return null
 */
protected DefaultPersistenceUnitManager getPersistenceUnitManager() {
    return persistenceUnitManager;
}
 
 类方法
 同包方法