Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to give persistenceUnitName for Spring's LocalContainerEntityManagerFactoryBean without persistence.xml?

I have multiple datasources and multiple EntityManagerFactories to be defined in my spring context.

If there is only on EntityManagerFactory we don't need to give persistenceUnitName. But to associate EntityManager to correct EntityManagerFactory with @PersistenceContext I should give unitName="somePU" attribute.

But if we give name for persistenceUnitName attribute then Spring is expecting these persistenceUnitName declarations in persistence.xml file.

Is there a way to give persistenceUnitName for Spring's LocalContainerEntityManagerFactoryBean without persistence.xml?

Also I found another issue when I used persistence.xml with Spring's LocalContainerEntityManagerFactoryBean. The packagesToScan property is not working. I need to list down all the Entity classes in persistence.xml.

Any idea why it is happening?

-siva

like image 901
K. Siva Prasad Reddy Avatar asked Oct 12 '12 08:10

K. Siva Prasad Reddy


People also ask

Does spring boot need persistence xml?

Spring Boot will not search for or use a META-INF/persistence. xml by default. If you prefer to use a traditional persistence. xml , you need to define your own @Bean of type LocalEntityManagerFactoryBean (with an ID of 'entityManagerFactory') and set the persistence unit name there.

Why do we need persistence xml?

The Java Persistence XML configuration file allows you to define a Persistence Unit configuration that you can later bootstrap using Java EE or Spring. Knowing all the persistence. xml file configuration options is very important as it allows you to address a great variety of mapping requirements.

Can we have multiple persistence xml?

The Java Persistence API allows you to define multiple persistence units, each of which can map to a separate database.

Where should I put the persistence xml?

xml should be put in the EJB JAR's META-INF directory. If you package the persistence unit as a set of classes in a WAR file, persistence. xml should be located in the WAR file's WEB-INF/classes/META-INF directory.


2 Answers

Specifying property in LocalContainerEntityManagerFactoryBean works for me

    <property name="persistenceUnitName" value="MyPersistenceUnit"/>
like image 162
Ondrej Bozek Avatar answered Sep 28 '22 04:09

Ondrej Bozek


After creating the LocalEntityManagerFactoryBean, set the persistence unit name:

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();

    factory.setPersistenceUnitName("NAME_OF_PERSISTENCE_UNIT");
like image 34
Filipe Ferreira Avatar answered Sep 28 '22 06:09

Filipe Ferreira