OpenJPA: How to configure EntityManager programmatically?

1.1k Views Asked by At

I try to configure my EntityManager programmatically. My vendor is OpenJPA and I write a simple console application. Here is my code

public static void main(String[] args) {
    Map<String, String> properties = new HashMap<>();

    properties.put("openjpa.ConnectionDriverName", "org.postgresql.Driver");
    properties.put("openjpa.ConnectionURL", "jdbc:postgresql://localhost:5432/shop");

    properties.put("openjpa.ConnectionUserName", "bob");
    properties.put("openjpa.ConnectionPassword", "secret");

    properties.put("openjpa.RuntimeUnenhancedClasses", "supported");
    properties.put("openjpa.MetaDataFactory", "jpa(Types=de.jpa.demo.dto.Category;de.jpa.demo.dto.User;de.jpa.demo.dto.Order;de.jpa.demo.dto.Product)");
    properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(foreignKeys=true)");

    EntityManagerFactory factory = Persistence.createEntityManagerFactory("test", properties);

    OpenJPAConfiguration configuration = ((EntityManagerFactoryImpl) factory).getConfiguration();
    MetaDataRepository repositoryInstance = configuration.getMetaDataRepositoryInstance();

    repositoryInstance.addPersistenceAware(Category.class);
    repositoryInstance.addPersistenceAware(Order.class);
    repositoryInstance.addPersistenceAware(Product.class);
    repositoryInstance.addPersistenceAware(User.class);

    manager = factory.createEntityManager();    
}

But I get an error

javax.persistence.PersistenceException: No persistence providers available for "test" after trying the following discovered implementations: org.apache.openjpa.persistence.PersistenceProviderImpl
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:182)
    at de.jpa.demo.dto.OpenJpaUserRepositoryIT.init(OpenJpaUserRepositoryIT.java:56)
    at de.jpa.demo.dto.OpenJpaUserRepositoryIT.before(OpenJpaUserRepositoryIT.java:22)

What I'm doing wrong?

1

There are 1 best solutions below

0
On

You must have a META-INF/persistence.xml file with a persistence unit named 'test' in it.

Also, please please please remove openjpa.RuntimeUnenhancedClasses property. It is a buggy feature and you'll be much happier if you take the time to figure out another enhancement strategy.