/**
   * Loads the persistence provider adapter
   *
   * @param persistenceProvider classloader will be used to load the persistence provider adapter
   * @return the persistence provider adaptor for the provider class
   */
  public static PersistenceProviderAdaptor loadPersistenceAdapter(
      PersistenceProvider persistenceProvider) {
    PersistenceProviderAdaptor persistenceProviderAdaptor = null;

    final ServiceLoader<PersistenceProviderAdaptor> serviceLoader =
        ServiceLoader.load(
            PersistenceProviderAdaptor.class, persistenceProvider.getClass().getClassLoader());

    if (serviceLoader != null) {
      for (PersistenceProviderAdaptor adaptor : serviceLoader) {
        if (persistenceProviderAdaptor != null) {
          throw MESSAGES.classloaderHasMultipleAdapters(
              persistenceProvider.getClass().getClassLoader().toString());
        }
        persistenceProviderAdaptor = adaptor;
        JPA_LOGGER.debugf(
            "loaded persistence provider adapter %s from classloader %s",
            persistenceProviderAdaptor.getClass().getName(),
            persistenceProvider.getClass().getClassLoader().toString());
      }
      if (persistenceProviderAdaptor != null) {
        persistenceProviderAdaptor.injectJtaManager(JtaManagerImpl.getInstance());
      }
    }

    return persistenceProviderAdaptor == null ? noopAdaptor : persistenceProviderAdaptor;
  }
  // Use info from the cached pUnitInfo and create a new EMF
  public EntityManagerFactory createEMF(Map<String, Object> props) {

    String unitName = pUnitInfo.getUnitName();
    debug("EMFProxy creating new EMF for ", unitName);
    PersistenceProvider provider = pUnitInfo.getAssignedProvider();
    EntityManagerFactory result = provider.createEntityManagerFactory(unitName, props);
    if (result == null)
      fatalError("Proxy could not create EMF " + unitName + " from provider " + provider, null);
    return result;
  }
Esempio n. 3
0
 public static void main(String[] args) {
   String email = "*****@*****.**";
   PersistenceProvider persistenceProvider = new HibernatePersistence();
   EntityManagerFactory entityManagerFactory =
       persistenceProvider.createEntityManagerFactory("NewPersistenceUnit", new HashMap());
   EntityManager entityManager = entityManagerFactory.createEntityManager();
   List<Customer> customers =
       entityManager
           .createQuery(SELECT_QUERY, Customer.class)
           .setParameter("email", email)
           .getResultList();
   System.out.println(customers);
   entityManager.close();
 }
  @Override
  @SuppressWarnings("unchecked")
  public EntityManagerFactory createContainerEntityManagerFactory(
      PersistenceUnitInfo info, Map properties) {
    properties.put("datanucleus.jpa.addClassTransformer", "false");
    properties.put(
        "datanucleus.plugin.pluginRegistryClassName", "org.datanucleus.plugin.OSGiPluginRegistry");

    info.addTransformer(
        new ClassTransformer() {

          @Override
          public byte[] transform(
              ClassLoader loader,
              String className,
              Class<?> classBeingRedefined,
              ProtectionDomain protectionDomain,
              byte[] classfileBuffer)
              throws IllegalClassFormatException {

            // TODO Auto-generated method stub
            return null;
          }
        });
    return pp.createContainerEntityManagerFactory(info, properties);
  }
  @Override
  protected EntityManagerFactory createNativeEntityManagerFactory() throws PersistenceException {
    PersistenceUnitManager managerToUse = this.persistenceUnitManager;
    if (this.persistenceUnitManager == null) {
      this.internalPersistenceUnitManager.afterPropertiesSet();
      managerToUse = this.internalPersistenceUnitManager;
    }

    this.persistenceUnitInfo = determinePersistenceUnitInfo(managerToUse);
    JpaVendorAdapter jpaVendorAdapter = getJpaVendorAdapter();
    if (jpaVendorAdapter != null && this.persistenceUnitInfo instanceof SmartPersistenceUnitInfo) {
      ((SmartPersistenceUnitInfo) this.persistenceUnitInfo)
          .setPersistenceProviderPackageName(jpaVendorAdapter.getPersistenceProviderRootPackage());
    }

    PersistenceProvider provider = getPersistenceProvider();
    if (provider == null) {
      String providerClassName = this.persistenceUnitInfo.getPersistenceProviderClassName();
      if (providerClassName == null) {
        throw new IllegalArgumentException(
            "No PersistenceProvider specified in EntityManagerFactory configuration, "
                + "and chosen PersistenceUnitInfo does not specify a provider class name either");
      }
      Class<?> providerClass = ClassUtils.resolveClassName(providerClassName, getBeanClassLoader());
      provider = (PersistenceProvider) BeanUtils.instantiateClass(providerClass);
    }
    if (provider == null) {
      throw new IllegalStateException(
          "Unable to determine persistence provider. "
              + "Please check configuration of "
              + getClass().getName()
              + "; "
              + "ideally specify the appropriate JpaVendorAdapter class for this provider.");
    }

    if (logger.isInfoEnabled()) {
      logger.info(
          "Building JPA container EntityManagerFactory for persistence unit '"
              + this.persistenceUnitInfo.getPersistenceUnitName()
              + "'");
    }
    this.nativeEntityManagerFactory =
        provider.createContainerEntityManagerFactory(this.persistenceUnitInfo, getJpaPropertyMap());
    postProcessEntityManagerFactory(this.nativeEntityManagerFactory, this.persistenceUnitInfo);

    return this.nativeEntityManagerFactory;
  }
 /** Setup the JPA provider. */
 public void setupProvider() {
   // Configure provider to be TopLink.
   String providerClass = "oracle.toplink.PersistenceProvider";
   PersistenceProvider provider = null;
   try {
     provider = (PersistenceProvider) Class.forName(providerClass).newInstance();
   } catch (Exception error) {
     throw new TestProblemException("Failed to create persistence provider.", error);
   }
   Map properties = new HashMap();
   properties.put("toplink.jdbc.driver", getSession().getLogin().getDriverClassName());
   properties.put("toplink.jdbc.url", getSession().getLogin().getConnectionString());
   properties.put("toplink.jdbc.user", getSession().getLogin().getUserName());
   properties.put("toplink.jdbc.password", getSession().getLogin().getPassword());
   properties.put("toplink.logging.level", getSession().getSessionLog().getLevelString());
   getExecutor()
       .setEntityManagerFactory(provider.createEntityManagerFactory("performance", properties));
 }
  @Test
  public void testJpa() throws Exception {
    final ServiceReference serviceReference =
        bundleContext.getServiceReference(PersistenceProvider.class.getName());
    final PersistenceProvider persistenceProvider =
        (PersistenceProvider) bundleContext.getService(serviceReference);
    final EntityManagerFactory emf =
        persistenceProvider.createEntityManagerFactory("hibernate-osgi-test", null);

    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    em.persist(new DataPoint("Brett"));
    em.getTransaction().commit();
    em.close();

    em = emf.createEntityManager();
    em.getTransaction().begin();
    DataPoint dp = em.find(DataPoint.class, 1);
    assertNotNull(dp);
    assertEquals("Brett", dp.getName());
    em.getTransaction().commit();
    em.close();

    em = emf.createEntityManager();
    em.getTransaction().begin();
    dp = em.find(DataPoint.class, 1);
    dp.setName("Brett2");
    em.getTransaction().commit();
    em.close();

    em = emf.createEntityManager();
    em.getTransaction().begin();
    em.createQuery("delete from DataPoint").executeUpdate();
    em.getTransaction().commit();
    em.close();

    em = emf.createEntityManager();
    em.getTransaction().begin();
    dp = em.find(DataPoint.class, 1);
    assertNull(dp);
    em.getTransaction().commit();
    em.close();
  }
Esempio n. 8
0
 /**
  * Create and return an EntityManagerFactory for the named persistence unit using the given
  * properties.
  *
  * @param persistenceUnitName The name of the persistence unit
  * @param properties Additional properties to use when creating the factory. The values of these
  *     properties override any values that may have been configured elsewhere.
  * @return The factory that creates EntityManagers configured according to the specified
  *     persistence unit.
  */
 public static EntityManagerFactory createEntityManagerFactory(
     String persistenceUnitName, Map properties) {
   EntityManagerFactory emf = null;
   if (providers.size() == 0) {
     try {
       findAllProviders();
     } catch (IOException exc) {
     }
     ;
   }
   for (PersistenceProvider provider : providers) {
     emf = provider.createEntityManagerFactory(persistenceUnitName, properties);
     if (emf != null) {
       break;
     }
   }
   if (emf == null) {
     throw new PersistenceException(
         "No Persistence provider for EntityManager named " + persistenceUnitName);
   }
   return emf;
 }
 /**
  * Create EE container entity manager factory
  *
  * @return EntityManagerFactory
  */
 private EntityManagerFactory createContainerEntityManagerFactory() {
   persistenceProviderAdaptor.beforeCreateContainerEntityManagerFactory(pu);
   try {
     return persistenceProvider.createContainerEntityManagerFactory(pu, properties.getValue());
   } finally {
     try {
       persistenceProviderAdaptor.afterCreateContainerEntityManagerFactory(pu);
     } finally {
       pu.setAnnotationIndex(
           null); // close reference to Annotation Index (only needed during call to
                  // createContainerEntityManagerFactory)
       // This is needed if the datasource is restarted
       // pu.setTempClassLoaderFactory(null);    // close reference to temp classloader factory
       // (only needed during call to createEntityManagerFactory)
     }
   }
 }
 /**
  * Create EE container entity manager factory
  *
  * @return EntityManagerFactory
  */
 private EntityManagerFactory createContainerEntityManagerFactory() {
   persistenceProviderAdaptor.beforeCreateContainerEntityManagerFactory(pu);
   try {
     JPA_LOGGER.tracef(
         "calling createContainerEntityManagerFactory for pu=%s with integration properties=%s, application properties=%s",
         pu.getScopedPersistenceUnitName(), properties.getValue(), pu.getProperties());
     return persistenceProvider.createContainerEntityManagerFactory(pu, properties.getValue());
   } finally {
     try {
       persistenceProviderAdaptor.afterCreateContainerEntityManagerFactory(pu);
     } finally {
       pu.setAnnotationIndex(
           null); // close reference to Annotation Index (only needed during call to
                  // createContainerEntityManagerFactory)
       // This is needed if the datasource is restarted
       // pu.setTempClassLoaderFactory(null);    // close reference to temp classloader factory
       // (only needed during call to createEntityManagerFactory)
     }
   }
 }
 @Override
 public void generateSchema(PersistenceUnitInfo info, Map map) {
   pp.generateSchema(info, map);
 }
 @Override
 public boolean equals(Object obj) {
   return pp.equals(obj);
 }
 @Override
 public int hashCode() {
   return pp.hashCode();
 }
 @Override
 public String getPersistentProviderClassName() {
   return pp.getClass().getName();
 }
 @Override
 public String toString() {
   return pp.toString();
 }
 public void activate(ComponentContext cc) {
   emf =
       persistenceProvider.createEntityManagerFactory(
           "org.opencastproject.capture.admin.impl.CaptureAgentStateServiceImpl",
           persistenceProperties);
 }
 @Override
 public boolean generateSchema(String persistenceUnitName, Map map) {
   return pp.generateSchema(persistenceUnitName, map);
 }
 @Override
 public ProviderUtil getProviderUtil() {
   return pp.getProviderUtil();
 }
Esempio n. 19
0
    @Override
    public EntityManagerFactory get() {
      PersistenceUnitInfo info =
          new PersistenceUnitInfo() {
            @Override
            public String getPersistenceUnitName() {
              String name = Thread.currentThread().getName();
              String id = getId();
              if (id == null) {
                name += "-default";
              } else {
                name += "-" + id;
              }
              return name;
            }

            @Override
            public String getPersistenceProviderClassName() {
              return null;
            }

            @Override
            public PersistenceUnitTransactionType getTransactionType() {
              return PersistenceUnitTransactionType.JTA;
            }

            @Override
            public DataSource getJtaDataSource() {
              return dataSource;
            }

            @Override
            public DataSource getNonJtaDataSource() {
              return null;
            }

            @Override
            public List<String> getMappingFileNames() {
              return Collections.emptyList();
            }

            @Override
            public List<URL> getJarFileUrls() {
              return Collections.emptyList();
            }

            @Override
            public URL getPersistenceUnitRootUrl() {
              try {
                return new URL("file:///Moonshine: please ignore this warning");
              } catch (MalformedURLException e) {
                throw new RuntimeException(e);
              }
            }

            @Override
            public List<String> getManagedClassNames() {
              List<String> names = new ArrayList<>();
              for (Class<?> klass : ClassIndex.getAnnotated(Entity.class)) {
                names.add(klass.getCanonicalName());
              }
              return names;
            }

            @Override
            public boolean excludeUnlistedClasses() {
              return true;
            }

            @Override
            public Properties getProperties() {
              Properties properties = new Properties();
              return properties;
            }

            @Override
            public ClassLoader getClassLoader() {
              return Thread.currentThread().getContextClassLoader();
            }

            @Override
            public void addTransformer(ClassTransformer transformer) {
              throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public ClassLoader getNewTempClassLoader() {
              return getClassLoader();
            }

            @Override
            public SharedCacheMode getSharedCacheMode() {
              return SharedCacheMode.UNSPECIFIED;
            }

            @Override
            public ValidationMode getValidationMode() {
              return ValidationMode.AUTO;
            }

            @Override
            public String getPersistenceXMLSchemaVersion() {
              return "";
            }
          };

      PersistenceProvider provider = new HibernatePersistence();

      Map<String, Object> map = new HashMap<>();
      map.put("hibernate.search.autoregister_listeners", false);
      if (plugins != null) {
        for (HibernatePlugin plugin : plugins) {
          map.putAll(plugin.getProperties());
        }
      }
      map.put(AvailableSettings.JTA_PLATFORM, jtaPlatform);
      map.put(AvailableSettings.HBM2DDL_AUTO, initSchema);
      map.put(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, useNewIdGeneratorMappings);
      map.put(AvailableSettings.USE_SQL_COMMENTS, useSqlComments);
      map.put(AvailableSettings.FORMAT_SQL, formatSql);
      map.put(AvailableSettings.SHOW_SQL, showSql);
      map.put("javax.persistence.validation.factory", validatorFactory);

      factory = provider.createContainerEntityManagerFactory(info, map);
      return factory;
    }