How to reference external hibernate.cfg.xml from persistence.xml - java

I have a JAR file that needs to be deployed into multiple environments, each with their own database connection parameters. Rightly or wrongly, I've been requested to make those database connection parameters external to the JAR. I've seen examples where persistence.xml can reference an external hibernate.cfg.xml that contains the specific connection parameters. Here's my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="myApp" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.ejb.cfgfile" value="./hibernate.cfg.xml" />
</properties>
</persistence-unit>
</persistence>
That external hibernate.ejb.cfg is located in the same folder as the JAR file, but the reference is failing. Here's the error I get:
DEBUG Ejb3Configuration - Look up for persistence unit: myApp
DEBUG Ejb3Configuration - Detect class: true; detect hbm: true
DEBUG Ejb3Configuration - Detect class: true; detect hbm: true
DEBUG Ejb3Configuration - Creating Factory: myApp
ERROR MyDaoImpl - initEntityManager() exception:
javax.persistence.PersistenceException: [PersistenceUnit: myApp] Unable to configure EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:265)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:125)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:52)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:34)
at com.touchnet.MyApp.server.dao.MyDaoImpl.initEntityManager(MyDaoImpl.java:486)
at com.touchnet.MyApp.server.dao.MyDaoImpl.getEntityManager(MyDaoImpl.java:457)
at com.touchnet.MyApp.server.dao.MyDaoImpl.getTransaction(MyDaoImpl.java:512)
at com.touchnet.MyApp.server.dao.MyDaoImpl.beginTransaction(MyDaoImpl.java:502)
at com.touchnet.MyApp.server.service.MyAppService.loadInputFile(MyAppService.java:346)
at com.touchnet.MyApp.server.commandLine.MyAppLoader.main(MyAppLoader.java:74)
at com.touchnet.MyApp.server.commandLine.MyAppLauncher.main(MyAppLauncher.java:44)
Caused by: org.hibernate.HibernateException: C:/MyApp/lib/hibernate.cfg.xml not found
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1411)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1433)
at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:972)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:753)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:191)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:253)
... 10 more
ERROR MyDaoImpl - No EntityManager configured.
DEBUG MyDaoImpl - getTransaction() returns null
ERROR MyDaoImpl - No Transaction configured.
How can I access that external hibernate.cfg.xml from persistence.xml?

The error here is
Caused by: org.hibernate.HibernateException: C:/MyApp/lib/hibernate.cfg.xml not found
As it was pointed out in a comment, it looks for it in the folder WEB-INF/clases
Copy the file to that folder and change the following line to:
<property name="hibernate.ejb.cfgfile" value="hibernate.cfg.xml" />
Cheers.

Related

Can not find the declaration of element 'persistence' , element persistence missing

Have put the persistence.xml in the classpath of the project in eclipse because before the error was that the file was not found. Now gives this error:
Caused by: javax.persistence.PersistenceException: Invalid persistence.xml. Error parsing XML [line : -1, column : -1] : cvc-elt.1: Can not find the declaration of element 'persistence'
here is my file:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.1"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="DataSource" transaction-type="JTA">
<description>JTA persistence unit related to the datasource DataSource</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.ejb.cfgfile" value="hibernate_DataSource.cfg.xml"/>
</properties>
</persistence-unit>
<persistence-unit name="securityStore" transaction-type="JTA">
<description>JTA persistence unit related to the datasource securityStore</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.ejb.cfgfile" value="hibernate_securityStore.cfg.xml"/>
</properties>
</persistence-unit>
</persistence>
According to the JPA spec (see section 8.2.1 persistence.xml file):
A persistence.xml file defines a persistence unit. The persistence.xml file is located in the META-INF directory of the root of the persistence unit.
So, try to put your persistence.xml in the META-INF directory.
P.S. Maybe you application actually use not the persistence.xml what you expect, but placed somewhere in the classpath in META-INF directory.

Can't use EJB from Web Application

I have the next problem while trying to develope a REST app using JPA and EJB's.
I have 3 projects in NetBeans (same workspace, just projects, not EAR or that weird stuff):
One of them is a Java Application in which I created some entity classes from a database. Inside of the same project, I created other package containing the controller classes from the entities. I tested the project creating a java main class and using the controllers.
The other project is a EJB module, it as simple as a package and the next class inside of it:
package com.studentejb;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import studentdao.StudentTO;
import studentdao.StudentJpaController;
#Stateless
#LocalBean
public class StudentEJB {
private StudentJpaController studentDao = new StudentJpaController();
public List<StudentTO> findStudents() {
return studentDao.findStudentTO();
}
}
As you can see, I imported the previous JAR project (the one with the entity's controllers). I also tested this EJB project with a java main class and it worked.
The last project is a web application, as you can imagine I want to use the EJB modules of the previous project but I get the following errors while trying to enter to the resource http://localhost:8080/studentWeb/student/:
12:00:12,384 ERROR [io.undertow.request] (default task-2) UT005023: Exception handling request to /studentWeb/student/hola: com.google.common.util.concurrent.ExecutionError: java.lang.ExceptionInInitializerError
at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2201)
at com.google.common.cache.LocalCache.get(LocalCache.java:3937)
at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3941)
at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4824)
at org.jboss.weld.util.cache.LoadingCacheUtils.getCacheValue(LoadingCacheUtils.java:49)
.
.
.
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ExceptionInInitializerError
at studentdao.StudentJpaController.<init>(StudentJpaController.java:40)
at com.studentejb.StudentEJB.<init>(StudentEJB.java:23)
at com.studentweb.Resources.<init>(Resources.java:52)
at com.studentweb.Resources$Proxy$_$$_WeldClientProxy.<init>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
.
.
.
... 58 more
Caused by: javax.persistence.PersistenceException: Unable to locate persistence units
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:99)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:86)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:67)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at studentdao.EntityProvider.<clinit>(EntityProvider.java:20)
... 80 more
Caused by: javax.persistence.PersistenceException: Invalid persistence.xml.
Error parsing XML [line : -1, column : -1] : cvc-elt.1.a: Cannot find the declaration of element 'persistence'.
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.validate(PersistenceXmlParser.java:377)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.loadUrl(PersistenceXmlParser.java:310)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.parsePersistenceXml(PersistenceXmlParser.java:114)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.doResolve(PersistenceXmlParser.java:104)
at org.hibernate.jpa.boot.internal.PersistenceXmlParser.locatePersistenceUnits(PersistenceXmlParser.java:86)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:95)
... 85 more
Here is the code of the web app (Resources.java):
#Path("/student")
public class Resources {
#EJB
private StudentEJB studentEjb;
#Context
private UriInfo context;
public Resources() throws FileNotFoundException, IOException, NamingException {
studentEjb = new StudentEJB();
}
#GET
#Path("/")
#Produces(MediaType.APPLICATION_JSON)
public Response getJson() {
return Response.ok(studentEjb.findStudents()).build();
}
}
So I am using 2 JARs for the web project, the one with the EJB modules and the other with the entities and controllers..
Here is the persistence.xml generated by the JPA project:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="studentJPAPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- <provider>org.hibernate.ejb.HibernatePersistence</provider> -->
<class>studentjpa.Address</class>
<class>studentjpa.Phone</class>
<class>studentjpa.Student</class>
<class>studentjpa.Email</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://localhost:1433;databaseName=tca_student_db;integratedSecurity=true"/>
<property name="javax.persistence.jdbc.user" value="xxxx"/>
<property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="javax.persistence.jdbc.password" value="xxxx"/>
</properties>
</persistence-unit>
</persistence>
Thank you!
Caused by: javax.persistence.PersistenceException: Invalid
persistence.xml. Error parsing XML [line : -1, column : -1] :
cvc-elt.1.a: Cannot find the declaration of element 'persistence'.
Here :
<persistence version="2.0" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
xmlns :http://xmlns.jcp.org/xml/ns/persistence doesn't match with the namespace in xsischemaLocation which is http://java.sun.com/xml/ns/persistence
Try to use the same in both :
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

What is wrong with this persistence unit configuration?

I am trying to set up a persistence unit in JEE 6 on JBoss AS 6.
The injected EntityManager is always null. I've fiddled around with the configuration quite a bit but can't get anything to work. I've tried JTA/LOCAL_RESOURCE, I've tried using a unit name in my code the same as in my persistence.xml, but also with the war name prepended, as the log suggests the JNDI name might be that.
I have a mysql-ds.xml file as follows:
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>myconnection</jndi-name>
<connection-url>jdbc:mysql://localhost:3306/cog1</connection-url>
<driver-class>org.gjt.mm.mysql.Driver</driver-class>
<user-name>bw</user-name>
<password></password>
<min-pool-size>2</min-pool-size>
<max-pool-size>20</max-pool-size>
<idle-timeout-minutes>5</idle-timeout-minutes>
<exception-sorter-class-name>com.mysql.jdbc.integration.jboss.ExtendedMysqlExceptionSorter</exception-sorter-class-name>
<valid-connection-checker-class-name>com.mysql.jdbc.integration.jboss.MysqlValidConnectionChecker</valid-connection-checker-class-name>
</local-tx-datasource>
</datasources>
I have a persistence.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="myunit" transaction-type="RESOURCE_LOCAL">
<jta-data-source>java:/myconnection</jta-data-source>
<non-jta-data-source>java:/myconnection</non-jta-data-source>
<class>com.cognitura.simulation.dao.model.History</class>
<properties>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.logging.level" value="INFO" />
</properties>
</persistence-unit>
</persistence>
And I have a bean with the following code in it:
#Stateful
#LocalBean
public class HistoryEJB {
#PersistenceContext(unitName = "myunit")
private EntityManager em;
#EJB
private RealityElement el;
I can see that the RealityElement el is getting injected fine, so I think it's definitely being container-managed?
Grateful for any ideas!
EDIT: The logs seem to be fine for setting up the 'myunit' unit. There is a warning, but I read that it's not important?
01:28:06,276 INFO [org.jboss.jpa.deployment.PersistenceUnitDeployment] Starting persistence unit persistence.unit:unitN
ame=cog1.war#myunit
01:28:06,278 INFO [org.hibernate.ejb.Ejb3Configuration] Processing PersistenceUnitInfo [
name: myunit
...]
01:28:06,305 WARN [org.hibernate.ejb.Ejb3Configuration] Persistence provider caller does not implement the EJB3 spec co
rrectly.PersistenceUnitInfo.getNewTempClassLoader() is null.
Seems happy here:
01:28:06,965 INFO [org.hibernate.impl.SessionFactoryObjectFactory] Bound factory to JNDI name: persistence.unit:unitNam
e=cog1.war#myunit
Could it be the jndi name? Try making the following changes in datasource and persistence files
<jndi-name>java:jboss/datasources/employeedb</jndi-name>
<jta-data-source>java:jboss/datasources/employeedb</jta-data-source>

Why Eclipse dont generate complete persistence.xml?

I have Vaadin project with JPA 2.1 + EclipseLink + MySQL.
In eclipse in project settings I set connection to base and drivers correctly. Without problem I "generate Entities from Tables", but persistence.xml haven't info about driver, connection, login, pass to DB.
My auto generate 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="RadiologicalWarehouse">
<class>pl.intibs.rw.entitites.Message</class>
<class>pl.intibs.rw.entitites.Part</class>
<class>pl.intibs.rw.entitites.Role</class>
<class>pl.intibs.rw.entitites.Sample</class>
<class>pl.intibs.rw.entitites.SampleHistory</class>
<class>pl.intibs.rw.entitites.User</class>
</persistence-unit>
</persistence>
If I run my application with simple query, I get of course exception:
javax.servlet.ServletException: com.vaadin.server.ServiceException: javax.persistence.PersistenceException: Exception [EclipseLink-4021] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: Unable to acquire a connection from driver [null], user [null] and URL [null]. Verify that you have set the expected driver class and URL. Check your login, persistence.xml or sessions.xml resource. The jdbc.driver property should be set to a class that is compatible with your database platform
com.vaadin.server.VaadinServlet.service(VaadinServlet.java:239)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
If JPA has defined the connection in the project, why does not generate this persistence automatically?
Screenshot settings JPA: http://i.imgur.com/T2oEdHA.png
Based on what I understand you have set parameters for the Jpa plugin to eclipse and this is much different to set the parameters to persistence provider. Firstly you have to decide what persitent provide use and specify it in the persistence.xml together with the others paramenters.
This is an example of persistence.xml with eclipseLink:
<persistence>
<persistence-unit name="myUnit">
<provider>yourProvider</provider>
<class>it.myCompany.domain.MyFirstClass</class>
<class>it.myCompany.domain.MySecondClassClass</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="${driverClass}" />
<property name="javax.persistence.jdbc.url" value="${connectionURL}" />
<property name="javax.persistence.jdbc.user" value="${username}" />
<property name="javax.persistence.jdbc.password" value="${password}" />
<property name="eclipselink.logging.level" value="info"/>
</properties>
<shared-cache-mode>NONE</shared-cache-mode>
</persistence-unit>
</persistence>

Open JPA Exception with Datasource in WAS 7.0 Java

I am getting Exception with Open JPA .
I have created WAS Data Source. Here is My Persistence XML
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="App11" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>java:comp/env/jdbc/mydatasource</jta-data-source>
<class>vo.Entity</class>
<properties>
<property name="openjpa.TransactionMode" value="managed"/>
<property name="openjpa.ConnectionFactoryMode" value="managed"/>
</properties>
</persistence-unit>
I am getting this exception while executing.
aused by: org.apache.commons.lang.exception.NestableRuntimeException: There was an error duing JNDI lookup of the name "java:comp/env/jdbc/mydatasource".
at org.apache.openjpa.lib.conf.Configurations.lookup(Configurations.java:592)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.lookupConnectionFactory(OpenJPAConfigurationImpl.java:966)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.getConnectionFactory(OpenJPAConfigurationImpl.java:954)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.createConnectionFactory(JDBCConfigurationImpl.java:801)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.getDBDictionaryInstance(JDBCConfigurationImpl.java:568)
at org.apache.openjpa.jdbc.meta.MappingRepository.endConfiguration(MappingRepository.java:1221)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:476)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:401)
at org.apache.openjpa.lib.conf.PluginValue.instantiate(PluginValue.java:102)
at org.apache.openjpa.lib.conf.ObjectValue.instantiate(ObjectValue.java:82)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.newMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:861)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.getMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:852)
at org.apache.openjpa.kernel.AbstractBrokerFactory.makeReadOnly(AbstractBrokerFactory.java:640)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:171)
Any help Appreciated.
Thanks,
Sam
Here is Solution of My Problem...
I was Missing this in web.xml
jdbc/Mysource javax.sql.DataSource Container Unshareable
Try adding resource-ref in your web.xml with runtime descriptor file (ibm-web-bnd.xml) as suggested in Websphere Datasource with a given JNDI name?

Categories

Resources