Overriding JPA persistence unit - java

I have an empty persistenceUnit in my jar file:
<persistence-unit transaction-type="JTA" name="base1">
</persistence-unit>
<persistence-unit transaction-type="JTA" name="base2">
</persistence-unit>
My idea is to replace the empty persistenceUnit by a full persistenceUnit with properties and classes in my main project, like this:
<persistence-unit name="base1" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>java:jboss/datasources/myDS</jta-data-source>
<class>br.com.myproject.MyClass</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<shared-cache-mode>NONE</shared-cache-mode>
<properties>
<property name="hibernate.hbm2ddl.auto" value="none" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="false" />
<property name="hibernate.cache.use_second_level_cache"
value="false" />
</properties>
</persistence-unit>
But when i try to start server i got the following error:
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYJPA0038: Falha ao adicionar o serviço da unidade de persistência para base1
Caused by: org.jboss.msc.service.DuplicateServiceException: Service jboss.persistenceunit.myproject#base1.__FIRST_PHASE__ is already registered"}}
Is there any way to override the persistenceUnit ?

If you really need to dynamically override your persistence.xml, this might be best done during building.
my personal warning: it sounds like a configuration-hell to me and I'd rather suggest using a container-managed JNDI approach here.
But anyway:
Use 2 maven profiles.
And if you activate profile1, then persistence.xml from profile1 will be added at the right place. and if you activate profile2 persistence.xml from profile2 will be taken.
therefore use the copy-resources-mojo for maven.
https://maven.apache.org/plugins/maven-resources-plugin/examples/copy-resources.html
If just the values of parameters change, and not the whole structure,
then you can also just "filter" and replace strings during maven-processes
then you would define properties in the profiles.
https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html
You can also add a basic persistence.xml to your project as a default file. So if no maven-profile is activated, this one will be used. (even though it might happen, that the app doesn't work as expected, if the data-resource is not configured correctly)

Spring provides an interface JpaVendorAdapter which allows to plug in any JPA vendor specific configuration through Spring Java config or XML configuration during application startup.
You can create an EntityManagerFactory instance with LocalContainerEntityManagerFactoryBean and any implementation classes of JpaVendorAdapter such as HibernateJpaVendorAdapter, EclipseLinkJpaVendorAdapter or OpenJpaVendorAdapter.
I believe you don't even need to define the empty persistence unit in persistence.xml if your application used Spring.
Below is the sample on how to create EntityManagerFactory with Spring Java config:
#Inject
private DataSource base1DataSource;
#Inject
private DataSource base2DataSource;
#Bean
public EntityManagerFactory base1EntityManagerFactory()
throws IOException, NamingException {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean containerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
containerEntityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
containerEntityManagerFactoryBean.setPackagesToScan("YOUR_PACKAGE_NAMES");
containerEntityManagerFactoryBean.setJtaDataSource(base1DataSource);
containerEntityManagerFactoryBean.setJpaProperties(loadBase1JpaProperties());
containerEntityManagerFactoryBean.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
containerEntityManagerFactoryBean.setPersistenceUnitName("base1");
containerEntityManagerFactoryBean.afterPropertiesSet();
return containerEntityManagerFactoryBean.getObject();
}
#Bean
public EntityManagerFactory base2EntityManagerFactory()
throws IOException, NamingException {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean containerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
containerEntityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
containerEntityManagerFactoryBean.setPackagesToScan("YOUR_PACKAGE_NAMES");
containerEntityManagerFactoryBean.setJtaDataSource(base2DataSource);
containerEntityManagerFactoryBean.setJpaProperties(loadBase2JpaProperties());
containerEntityManagerFactoryBean.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
containerEntityManagerFactoryBean.setPersistenceUnitName("base2");
containerEntityManagerFactoryBean.afterPropertiesSet();
return containerEntityManagerFactoryBean.getObject();
}
#Bean
public Properties loadBase1JpaProperties() throws IOException {
ClassPathResource resource = new ClassPathResource("base1-persistence.properties");
return PropertiesLoaderUtils.loadProperties(resource);
}
#Bean
public Properties loadBase2JpaProperties() throws IOException {
ClassPathResource resource = new ClassPathResource("base2-persistence.properties");
return PropertiesLoaderUtils.loadProperties(resource);
}
Please refer to the following URL for additional info on what you can override to your persistence.xml :
http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBean.html

I assume you want to declare your persistent unit in a superclass and you want to define the persistent unit in a explicit project. If true you could use a JNDI approch like this:
<persistence-unit name="MyPersistenceUnit"
transaction-type="JTA">
<jta-data-source>java:/myDS</jta-data-source>
<mapping-file>META-INF/orm.xml</mapping-file>
<jar-file>Persistence.jar</jar-file>
<properties>
<property name="jboss.entity.manager.jndi.name" value="java:app/applicationEntitymanager"/>
<!-- Properties for Hibernate -->
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
on the other side you can acces the Entitymanager with:
#Resource(mappedName = "java:app/applicationEntitymanager")
protected EntityManager em;

Related

Ejb wont initialize entity manager

my english is not my native language so i am sorry in advanced for my poor english.
My project is working well when i manage the transaction with entity manager, entity factory and get transactions.
I want to use the ejb to handle the transactions for me.
I did every thing needed in order for it to work but the ejb wont initalized the entity manager and he will stay null.
i cant understand what i am doing wrong.
i have configured my persistance.xml with jta data source and did all the annotations needed but still cant get it to work.
what i try to create a query i get a null pointer exception and the entity manager is null.
I have been searching and looking for a solution but did not succeed.
I hope some one here can find the answer.
Thank you for you time!
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="swap" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/swap</jta-data-source>
<class>org.Roper.WebService.Model.User</class>
<class>org.Roper.WebService.Model.BaseEntity</class>
<class>org.Roper.WebService.Model.Person</class>
<class>org.Roper.WebService.Model.Admin</class>
<class>org.Roper.WebService.Model.BusinessOwner</class>
<class>org.Roper.WebService.Model.Business</class>
<class>org.Roper.WebService.Model.Product</class>
<class>org.Roper.WebService.Model.Category</class>
<class>org.Roper.WebService.Model.Tourist</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<!-- Hibernate properties -->
<property name="javax.persistence.jdbc.driver"
value="org.postgresql.Driver" /> <!-- DB Driver -->
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.connection.zeroDateTimeBehavior"
value="convertToNull" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.transaction.jta.platform"
value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform" />
<!-- Database properties -->
<property name="javax.persistence.jdbc.url"
value="jdbc:postgresql://hidden/swap?useUnicode=yes&characterEncoding=UTF-8" /> <!-- BD Mane -->
<property name="javax.persistence.jdbc.user" value="hidden" /> <!-- DB User -->
<property name="javax.persistence.jdbc.password"
value="hidden" /> <!-- DB Password -->
</properties>
</persistence-unit>
</persistence>
This is the main class that call the ejb:
#Path("PersonService")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class PersonResource {
private static final Logger logger = Logger.getLogger(PersonResource.class);
#EJB
PersonService personService = new PersonService();
#GET
#Path("/users")
public List<Person> getUsers(#BeanParam FilterBean fb)
{
logger.info("Getting all users.");
return personService.GetAllUsers();
}
}
this is the service class that call the entity managet:
#Stateless
#LocalBean
public class PersonService {
private static final Logger logger = Logger.getLogger(PersonService.class);
#PersistenceContext(unitName="swap")
public EntityManager em;
/**
*This function is querying the database selecting all the person entities.
*#return List of all the users from the database.
*/
public List<Person> GetAllUsers()
{
logger.debug("Starting to get all users.");
try {
try {
List<Person> users = em.createQuery("SELECT u FROM Person u").getResultList();
logger.info("Success, got all users.");
return new ArrayList<Person>(users);
}
catch(PersistenceException e)
{
if(e.getCause().getCause().getMessage().contains("ERROR: relation \"users\" does not exist"))
{
logger.info("No users in the database.");
}
else
{
logger.error("Error while getting users from the database, error: ", e);
}
}
}catch(Exception e)
{
logger.error("Cant get the users, error: ",e);
}
return null;
}
The datasource from the standalone-full.xml:
<subsystem xmlns="urn:jboss:domain:datasources:5.0">
<datasources>
<datasource jndi-name="java:jboss/datasources/swap" pool-name="swap" enabled="true" use-java-context="true">
<connection-url>jdbc:postgresql://127.0.0.1:5432/swap?useUnicode=yes&characterEncoding=UTF-8</connection-url>
<driver>org.postgresql</driver>
<security>
<user-name>postgres</user-name>
<password>postgres</password>
</security>
</datasource>
<drivers>
<driver name="org.postgresql" module="org.postgresql">
<driver-class>org.postgresql.Driver</driver-class>
<xa-datasource-class>org.postgresql.Driver</xa-datasource-class>
</driver>
</drivers>
</datasources>
</subsystem>
Following lines look suspicious:
#EJB
PersonService personService = new PersonService();
It should be either injected (so no = new PersonService();is needed) or created via constructor but that instance is not managed by any container and, as a consequence, no injection happens there and EntityManager em stays null.
Please update your code as follows:
#EJB
PersonService personService;
Beside that, Integrating JAX-RS with EJB Technology and CDI section of JavaEE 6 tutorial suggests that JAX-RS resources should be either EJBs themselves (so annotated with #Stateless or #Stateful) OR CDI beans (so annotated with #ApplicationScoped or #RequestScoped). I would suggest to add a #Stateless annotation on the PersonResource class itself.

joinTransaction has been called on a resource-local EntityManager in ApacheCamel

I am new to apache camel and I am testing camel-jpa to poll from table and display records
Following is main class
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("LoanServicePU");
CamelContext camelContext = new DefaultCamelContext();
JpaComponent jpa = new JpaComponent();
jpa.setEntityManagerFactory(entityManagerFactory);
JpaTransactionManager myTM=new JpaTransactionManager();
myTM.setEntityManagerFactory(entityManagerFactory);
jpa.setTransactionManager( myTM );
jpa.setCamelContext(camelContext);
camelContext.addRoutes(new JpaRouteBuilder());
camelContext.addComponent("jpa",jpa);
camelContext.start();
Thread.sleep(10000);
camelContext.stop();
System.out.println("Done");
Following is jparouter class
public void configure() throws Exception {
from("jpa://com.pns.ab.model.LoanRequest?consumeDelete=false;"
+ "consumer.delay=2000;maxMessagesPerPoll=1000;"
+ "consumer.namedQuery=selectLoanRequests").to("stream:out");
}
I configured persistence.xml and its under META-INF, in fact in eclipse I start Java Project and then set JPA facet
persistence.xml
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="LoanServicePU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.pns.ab.model.LoanRequest</class>
<properties>
<property name="eclipselink.target-server" value="None"/>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:#127.0.0.1:1521:xe"/>
<property name="javax.persistence.jdbc.user" value="vs"/>
<property name="javax.persistence.jdbc.password" value="vs"/>
<property name="eclipselink.logging.level" value="INFO"/>
</properties>
</persistence-unit>
</persistence>
But I am getting following error:
[main] INFO org.apache.camel.impl.DefaultCamelContext - Apache Camel 2.12.3 (CamelContext: camel-1) started in 1.426 seconds
[Camel (camel-1) thread #0 - jpa://com.pns.ab.model.LoanRequest] WARN org.apache.camel.component.jpa.JpaConsumer - Consumer Consumer[jpa://com.pns.ab.model.LoanRequest?consumeDelete=false%3Bconsumer.delay%3D2000&consumer.namedQuery=selectLoanRequests] failed polling endpoint: Endpoint[jpa://com.pns.ab.model.LoanRequest?consumeDelete=false%3Bconsumer.delay%3D2000&consumer.namedQuery=selectLoanRequests]. Will try again at next poll. Caused by: [javax.persistence.TransactionRequiredException - joinTransaction has been called on a resource-local EntityManager which is unable to register for a JTA transaction.]
javax.persistence.TransactionRequiredException: joinTransaction has been called on a resource-local EntityManager which is unable to register for a JTA transaction.
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionWrapper.registerIfRequired(EntityTransactionWrapper.java:91)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.joinTransaction(EntityManagerImpl.java:2081)
From the log
resource-local EntityManager which is unable to register for a JTA transaction
I conclude that the camel route is deployed to a JTA transaction environment but that in your persistence.xml you may use the default transaction-type which is RESOURCE_LOCAL instead of JTA.
EDIT:
With following setup, I could make it work:
Don't init the EntityManagerFactory and TransactionManager yourself, just do:
final SimpleRegistry registry = new SimpleRegistry();
final CamelContext context = new DefaultCamelContext(registry);
context.addRoutes(new JpaSetupRouteBuilder());
context.start();
In persistence.xml rename your persistence-unit to camel such as:
<!-- setting the transaction-type to RESOURCE_LOCAL is optional as this is the default -->
<persistence-unit name="camel" transaction-type="RESOURCE_LOCAL">
Yes, I know, this is not very satisfying.
EDIT:
If you don't want to or are not able to rename the persistence-unit to camel then you could set its name in the URI using the persistenceUnit option such as:
from("jpa://com.pns.ab.model.LoanRequest?consumeDelete=false"
+ "&consumer.delay=2000;maxMessagesPerPoll=1000"
+ "&consumer.namedQuery=selectLoanRequests"
+ "&persistenceUnit=LoanServicePU")
.to("stream:out");
EDIT:
Or alternatively, use the Spring XML setup as described here.

Changing Persistence Unit dynamically - JPA

Persistence units in persistence.xml are created during building the application. As I want to change the database url at runtime, is there any way to modify the persistence unit at runtime? I supposed to use different database other than pre-binded one after distributed.
I'm using EclipseLink (JPA 2.1)
Keep the persistence unit file (Persistence.xml) as it's. You can override the properties in it as follows.
EntityManagerFactory managerFactory = null;
Map<String, String> persistenceMap = new HashMap<String, String>();
persistenceMap.put("javax.persistence.jdbc.url", "<url>");
persistenceMap.put("javax.persistence.jdbc.user", "<username>");
persistenceMap.put("javax.persistence.jdbc.password", "<password>");
persistenceMap.put("javax.persistence.jdbc.driver", "<driver>");
managerFactory = Persistence.createEntityManagerFactory("<current persistence unit>", persistenceMap);
manager = managerFactory.createEntityManager();
You can use Persistence.createEntityManagerFactory(Map) to pass properties to choose the database URL and other settings.
In Long-lived Session Architecture you should create a Plug-in-Framework.
Therefore you need to create a different Thread-Group and Class-Repository.
This might be your Class-Loader-Tree
System-Class-Loader (usually a URLClassLoader, contains the Entitys)
JPA-Class-Loader
Load your jpa.jar with persistence.xml inside, specify the Database-Configuration from Application-Class-Loader
Instanciate your entityManager/session-factory.
Load any plugin you need to work with the DataBase. Execute Unit-Tests (;D) and Plugin-Integration-Tests.
If you are using Thorntail framework, you can wire-up the persistence.xml file to fetch runtime variables from "project-defaults.yml" file.
<persistence-unit name="java:jboss/datasources/my-postgres-ds">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.package.jpa.EntityClass1</class>
<class>com.package.jpa.EntityClass2</class>
<class>com.package.jpa.EntityClass3</class>
<properties>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.connection.url"
value="${thorntail.datasources.data-sources.my-postgres-ds.connection-url}"/>
<property name="hibernate.connection.username"
value="${thorntail.datasources.data-sources.my-postgres-ds.user-name}"/>
<property name="hibernate.connection.password"
value="${thorntail.datasources.data-sources.my-postgres-ds.password}"/>
<property name="hibernate.default_schema" value="public"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
Take note of the dynamic DB values in ${...} as the point to values in the project-default.yml file.
Then you project-defaults.yml file will have an entry like this:
thorntail:
http:
port: 8989
datasources:
data-sources:
my-postgres-ds:
driver-name: my-postgres-driver
connection-url: "jdbc:postgresql://localhost:5432/my-db-name"
user-name: my-user-name
password: "my-password#"
jdbc-drivers:
my-postgres-driver:
driver-module-name: org.postgresql
driver-xa-datasource-class-name: org.postgresql.xa.PGXADataSource
I expect this should also work for Spring boot using application.properties and persistence.xml

Datanucleus warning: Class was specified in persistence-unit but not annotated, so ignoring

When starting up my app I see for every class this warning:
WARN [DataNucleus.MetaData] - Class com.mycomp.MyClass was specified in persistence-unit myPersistenceUnit but not annotated, so ignoring
The app starts up correctly so there is no direct issue, but I'm wondering where this coming form, and how to avoid id.
My persistence.xml looks like:
<persistence-unit name="myPersistenceUnit">
<provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
<properties>
<property name="datanucleus.ConnectionURL" value="appengine" />
<property name="datanucleus.NontransactionalRead" value="true" />
<property name="datanucleus.NontransactionalWrite" value="true" />
<property name="datanucleus.appengine.datastoreEnableXGTransactions" value="true" />
<property name="datanucleus.jpa.addClassTransformer" value="false" />
</properties>
</persistence-unit>
I'm running my app on Google App Engine with Spring.
But I can't find the origin of the warnings.
Something seems to be telling my app to do some check for all classes.
PS: I'm defining my entityManagerFactory as follows:
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setPersistenceUnitName("myPersistenceUnit");
entityManagerFactory.setPersistenceUnitPostProcessors(new ClasspathScanningPersistenceUnitPostProcessor("com.mycomp.domain"));
return entityManagerFactory;
}
Any help appreciated.
You aren't including any < jar-file > or < class > tags in your persistence.xml, so my guess is that your application is searching for Entities in all the classes it can reach. Maybe you are mixing Entity with non-Entity classes in the same java package. You don't say much about the pacakges or your classes really.

Problem on jboss lookup entitymanager

I have my ear-project deployed in jboss 5.1GA.
From webapp i don't have problem, the lookup of my ejb3 work fine!
es:
ShoppingCart sc= (ShoppingCart)
(new InitialContext()).lookup("idelivery-ear-1.0/ShoppingCartBean/remote");
also the iniection of my EntityManager work fine!
#PersistenceContext
private EntityManager manager;
From test enviroment (I use Eclipse) the lookup of the same ejb3 work fine!
but the lookup of entitymanager or PersistenceContext don't work!!!
my good test case:
public void testClient() {
Properties properties = new Properties();
properties.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
properties.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
properties.put("java.naming.provider.url","localhost");
Context context;
try{
context = new InitialContext(properties);
ShoppingCart cart = (ShoppingCart) context.lookup("idelivery-ear-1.0/ShoppingCartBean/remote"); // WORK FINE
} catch (Exception e) {
e.printStackTrace();
}
}
my bad test :
EntityManagerFactory emf = Persistence.createEntityManagerFactory("idelivery");
EntityManager em = emf.createEntityManager(); //test1
EntityManager em6 = (EntityManager) new InitialContext().lookup("java:comp/env/persistence/idelivery"); //test2
PersistenceContext em3 = (PersistenceContext)(new InitialContext()).lookup("idelivery/remote"); //test3
my persistence.xml
<persistence-unit name="idelivery" transaction-type="JTA">
<jta-data-source>java:ideliveryDS</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop" /><!--validate | update | create | create-drop-->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
my datasource:
<datasources>
<local-tx-datasource>
<jndi-name>ideliveryDS</jndi-name>
...
</local-tx-datasource>
</datasources>
I need EntityManager and PersistenceContext to test my query before build ejb...
Where is my mistake?
Server-side EntityManager cannot be serialized so that you can use it as a client side EntityManager. That would mean that EntityManager referenced on the client-side still can talk to the database, use connection pool, etc. It is impossible (think of firewall, which protects database server, for instance).
If you need to test JPA, use local EntityManager without JTA transactions. If you want to test EJBs you need to simulate whole EJB container. You can use Spring Pitchfork or Glassfish 3 embedded container (the latter option is easier).
I need to test JPA, use local EntityManager without JTA transactions!
I followed your suggestion:I created new persistence.xml with a new persistence-unit
<persistence-unit name="ideliveryTest" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>it.idelivery.model.Category</class>
<class>it.idelivery.model.User</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/application"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value=""/>
</properties>
</persistence-unit>
and in my test case:
try {
logger.info("Building JPA EntityManager for unit tests");
emFactory = Persistence.createEntityManagerFactory("ideliveryTest");
em = emFactory.createEntityManager();
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception during JPA EntityManager instanciation.");
}
work fine!
In my maven project i put persistence.xml with persistence-unit type="RESOURCE_LOCAL" in src/test/resources
and i put persistence.xml with persistence-unit type="JTA" in src/main/resources
by this way I have two separates enviroment. One for test and one for production.
it's a best practice?

Categories

Resources