create entity manager programmatically without persistence file
Asked Answered
I

2

6

I'm trying to create entity Factory manager programmatically without persistence file

    EntityManagerFactory emf;
    Map<String, String> properties = new HashMap<String, String>();
    properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
    properties.put("hibernate.connection.url", "jdbc:mysql://173.194.25***************");
    properties.put("hibernate.connection.username", "etech****");
    properties.put("hibernate.connection.password", "A*****");
    properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    properties.put("hibernate.show-sql", "true");
    properties.put("provider", "org.hibernate.ejb.HibernatePersistence");
    emf = Persistence.createEntityManagerFactory(idClient, properties);

On line

emf = Persistence.createEntityManagerFactory(idClient, properties);

I am getting the error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com****RepositoryFieldsFieldWorkerRepositoryImpl': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: No Persistence provider for EntityManager named idClient

How can i resolve this problem ?

any help will be appreciated

Interject answered 3/4, 2015 at 14:30 Comment(2)
Visual changes ? what this mean ?Interject
Actually that comment was intended to be in the box where I told you what changes I suggested when editing ...Indiscernible
O
20

Here is a pure programmatic way to build an entity manager without spring and without a persistence.xml. Constants are taken from org.hibernate.cfg.AvailableSettings :

entityManagerFactory = new HibernatePersistenceProvider().createContainerEntityManagerFactory(
            archiverPersistenceUnitInfo(),
            ImmutableMap.<String, Object>builder()
                    .put(JPA_JDBC_DRIVER, JDBC_DRIVER)
                    .put(JPA_JDBC_URL, JDBC_URL)
                    .put(DIALECT, Oracle12cDialect.class)
                    .put(HBM2DDL_AUTO, CREATE)
                    .put(SHOW_SQL, false)
                    .put(QUERY_STARTUP_CHECKING, false)
                    .put(GENERATE_STATISTICS, false)
                    .put(USE_REFLECTION_OPTIMIZER, false)
                    .put(USE_SECOND_LEVEL_CACHE, false)
                    .put(USE_QUERY_CACHE, false)
                    .put(USE_STRUCTURED_CACHE, false)
                    .put(STATEMENT_BATCH_SIZE, 20)
                    .build());

entityManager = entityManagerFactory.createEntityManager();

And the infamous PersistenceUnitInfo

private static PersistenceUnitInfo archiverPersistenceUnitInfo() {
    return new PersistenceUnitInfo() {
        @Override
        public String getPersistenceUnitName() {
            return "ApplicationPersistenceUnit";
        }

        @Override
        public String getPersistenceProviderClassName() {
            return "org.hibernate.jpa.HibernatePersistenceProvider";
        }

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

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

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

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

        @Override
        public List<URL> getJarFileUrls() {
            try {
                return Collections.list(this.getClass()
                                            .getClassLoader()
                                            .getResources(""));
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

        @Override
        public URL getPersistenceUnitRootUrl() {
            return null;
        }

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

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

        @Override
        public SharedCacheMode getSharedCacheMode() {
            return null;
        }

        @Override
        public ValidationMode getValidationMode() {
            return null;
        }

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

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

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

        @Override
        public void addTransformer(ClassTransformer transformer) {

        }

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

Note that Spring offers streamlined way to configure the persistence, while supporting multiple hibernate versions. (Spring 4.2 supports Hibernate up to 5.1, Spring 4.3 supports Hibernate up to 5.2).

Obsequious answered 21/2, 2017 at 16:33 Comment(3)
Awesome! Thanks.Hellenism
We can pass in the username and password as well in the ImmutableMapImmutableMap.<String, Object>builder() .put(JPA_JDBC_DRIVER, "oracle.jdbc.driver.OracleDriver") .put(JPA_JDBC_URL, "<your DB connection details>") .put(DIALECT, Oracle12cDialect.class) .put(JPA_JDBC_USER, "<conneting user>") .put(JPA_JDBC_PASSWORD, "<user's password>") .build());Genro
Thanks. Sometimes the provider varies; in my case(non-Spring project), it's org.hibernate.ejb.HibernatePersistence.Cryptoanalysis
S
1

A persistence.xml file is mandatory to create your persistence unit at deployment time as per the JPA specs.

See Create JPA EntityManager without persistence.xml configuration file

Suspension answered 3/4, 2015 at 15:35 Comment(5)
i created a persistence.xml file but i have the same problem <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="java.sun.com/xml/ns/persistence" xmlns:xsi="w3.org/2001/XMLSchema-instance" xsi:schemaLocation="java.sun.com/xml/ns/persistence java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="idClient"> <provider>javax.persistence.spi.PeristenceProvider</provider> </persistence-unit> </persistence>Interject
have you redeployed your app ? the logs shall contain a confirmation that the PU has been loaded properly. You don't need to specify the provider in the persistence.xml file if you specify it when creating the Emf. Or better, if you do not need to change them at runtime, put all properties in the persistence.xml fileSuspension
i delete tomcat and mvn clean install and redeployed it same problem :(Interject
i have to do that dynamically so ideally all properties must be in codeInterject
That is not true. It is possible to bootstrap JPA without a persistence.xml : docs.jboss.org/hibernate/orm/5.2/userguide/html_single/chapters/…Obsequious

© 2022 - 2024 — McMap. All rights reserved.