Multiple datasources in war: Unable to acquire JDBC Connection - jpa

Environment:
Wildfly 10
Java 8
I have a war project with a persistence unit(OracleDS) that access to a ejb.jar with another persistence unit(MySqlDS).
The server has configured both datasources as Non-XA.
The default transaction management is type Container, but if I use Transaction ManagementType.BEAN at class level it seems to work.
Why is that working? WHat is the difference with the Container type?
Code in #Stateless class
public void test() {
Espacio espacioBase = espacioMgr.findByCodEspai(1); //EJB with 1st datasource
Servei servei = ServeiMgr.findById(1); //EJB with 2nd datasource ERROR
}
Espacio.java new.war
#Entity
#Table(name = "V_ESPACIOS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = Espacio.findByCodEspai, query = "SELECT e FROM Espacio e WHERE e.codespai = :codespai")})
public class Espacio implements Serializable {
private static final long serialVersionUID = 1L;
public static final String findByTipus = "Espacio.findByTipus";
public static final String findByCodEspaiPare = "Espacio.findByCodEspaiPare";
public static final String findByNom = "Espacio.findByNom";
public static final String findAll = "Espacio.findAll";
public static final String findByCodEspai = "Espacio.findByCodEspai";
public static final String findChildrenByCodEspai = "Espacio.findChildrenByCodEspai";
...
Servei.java ejb.jar
#Entity
#Table(name = "a_servei")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = Servei.findAll, query = "SELECT s FROM Servei s")})
public class Servei implements Serializable, Comparable<Servei> {
private static final long serialVersionUID = -1979740551238968079L;
static final String PREFIX = "pia.entity.Servei.";
public static final String findAll = PREFIX + "findAll";
...
ServeiManager
#Stateless
public class ServeiManager {
protected Logger logger = Logger.getLogger(getClass().getName());
#PersistenceContext(unitName = "onePU")
protected EntityManager em;
public List<Servei> all() {
return this.em.createNamedQuery(Servei.findAll, Servei.class).
getResultList();
}
...
EspacioManager
#Stateless
public class EspacioManager {
protected Logger logger = Logger.getLogger(getClass().getName());
#PersistenceContext(unitName = "twoPU")
protected EntityManager em;
public Espacio findByCodEspai(int codEspai) {
return this.em.createNamedQuery(Espacio.findByCodEspai, Espacio.class).
setParameter("codespai", codEspai).
getSingleResult();
}
...
persistence.xml new.war
<?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="twoPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/jboss/datasources/OracleDS</jta-data-source>
<properties>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
</properties>
</persistence-unit>
</persistence>
persistence.xml ejb.jar
<?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="onePU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/MySqlDS</jta-data-source>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
</persistence>
Error
09:24:46,961 WARN [com.arjuna.ats.arjuna] (default task-18) ARJUNA012140: Adding multiple last resources is disallowed. Trying to add LastResourceRecord(XAOnePhaseResource(LocalXAResourceImpl#425d04d5[connectionListener=1949f99c connectionManager=76ebb8c8 warned=false currentXid=< formatId=131077, gtrid_length=29, bqual_length=36, tx_uid=0:ffff7f000101:2b71c2d2:5a701dd6:13d, node_name=1, branch_uid=0:ffff7f000101:2b71c2d2:5a701dd6:143, subordinatenodename=null, eis_name=java:jboss/datasources/MySqlDS > productName=MySQL productVersion=5.5.44-MariaDB-log jndiName=java:jboss/datasources/MySqlDS])), but already have LastResourceRecord(XAOnePhaseResource(LocalXAResourceImpl#47bca654[connectionListener=2b07cb93 connectionManager=214b627a warned=false currentXid=< formatId=131077, gtrid_length=29, bqual_length=36, tx_uid=0:ffff7f000101:2b71c2d2:5a701dd6:13d, node_name=1, branch_uid=0:ffff7f000101:2b71c2d2:5a701dd6:141, subordinatenodename=null, eis_name=java:jboss/datasources/OracleDS > productName=Oracle productVersion=Oracle Database 11g Release 11.2.0.4.0 - 64bit Production
With the Automatic Storage Management option jndiName=java:jboss/datasources/OracleDS]))
09:24:46,966 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-18) SQL Error: 0, SQLState: null
09:24:46,967 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-18) javax.resource.ResourceException: IJ000457: Unchecked throwable in managedConnectionReconnected() cl=org.jboss.jca.core.connectionmanager.listener.TxConnectionListener#1949f99c[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection#33011f78 connection handles=0 lastReturned=1517300686965 lastValidated=1517297117411 lastCheckedOut=1517300686959 trackByTx=false pool=org.jboss.jca.core.connectionmanager.pool.strategy.OnePool#35406018 mcp=SemaphoreConcurrentLinkedQueueManagedConnectionPool#2e374d12[pool=MySqlDS] xaResource=LocalXAResourceImpl#425d04d5[connectionListener=1949f99c connectionManager=76ebb8c8 warned=false currentXid=null productName=MySQL productVersion=5.5.44-MariaDB-log jndiName=java:jboss/datasources/MySqlDS] txSync=null]
09:24:46,970 INFO [org.hibernate.event.internal.DefaultLoadEventListener] (default task-18) HHH000327: Error performing load command : org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
09:24:47,057 ERROR [org.jboss.as.ejb3.invocation] (default task-18) WFLYEJB0034: EJB Invocation failed on component ServeiManager for method public es.imas.ada.business.gestio.entity.Servei es.imas.ada.business.gestio.boundary.ServeiManager.findById(int): javax.ejb.EJBTransactionRolledbackException: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
... more
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
... more
Caused by: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
... more
Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000457: Unchecked throwable in managedConnectionReconnected() cl=org.jboss.jca.core.connectionmanager.listener.TxConnectionListener#1949f99c[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection#33011f78 connection handles=0 lastReturned=1517300686965 lastValidated=1517297117411 lastCheckedOut=1517300686959 trackByTx=false pool=org.jboss.jca.core.connectionmanager.pool.strategy.OnePool#35406018 mcp=SemaphoreConcurrentLinkedQueueManagedConnectionPool#2e374d12[pool=MySqlDS] xaResource=LocalXAResourceImpl#425d04d5[connectionListener=1949f99c connectionManager=76ebb8c8 warned=false currentXid=null productName=MySQL productVersion=5.5.44-MariaDB-log jndiName=java:jboss/datasources/MySqlDS] txSync=null]
... 240 more
Caused by: javax.resource.ResourceException: IJ000457: Unchecked throwable in managedConnectionReconnected() cl=org.jboss.jca.core.connectionmanager.listener.TxConnectionListener#1949f99c[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection#33011f78 connection handles=0 lastReturned=1517300686965 lastValidated=1517297117411 lastCheckedOut=1517300686959 trackByTx=false pool=org.jboss.jca.core.connectionmanager.pool.strategy.OnePool#35406018 mcp=SemaphoreConcurrentLinkedQueueManagedConnectionPool#2e374d12[pool=MySqlDS] xaResource=LocalXAResourceImpl#425d04d5[connectionListener=1949f99c connectionManager=76ebb8c8 warned=false currentXid=null productName=MySQL productVersion=5.5.44-MariaDB-log jndiName=java:jboss/datasources/MySqlDS] txSync=null]
... 244 more
Caused by: javax.resource.ResourceException: IJ000461: Could not enlist in transaction on entering meta-aware object
... 246 more
Caused by: javax.transaction.SystemException: IJ000356: Failed to enlist: java.lang.Throwable: Unabled to enlist resource, see the previous warnings. tx=TransactionImple < ac, BasicAction: 0:ffff7f000101:2b71c2d2:5a701dd6:13d status: ActionStatus.ABORT_ONLY >
... 247 more

Related

EclipseLink 3.0 doesn't find a suitable jdbc (Jakarta EE)

I'm trying to run a simple web application on which I want run some tests on Jakarta EE 9.1(Full platform). I deployed my application on Glassfish 6.2.5. While I was running some code with jpa implementation this exception is thrown(the persistence provider is EclipseLink 3.0.2):
jakarta.persistence.PersistenceException: Exception [EclipseLink-4002]
(Eclipse Persistence Services - 3.0.2.v202107160933):
org.eclipse.persistence.exceptions.DatabaseException Internal
Exception: java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306;create=true Error Code: 0
The persistence.xml is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"
version="3.0">
<persistence-unit name="GestoreDB" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>testJPA.ValueBeen</class>
<properties>
<property name="jakarta.persistence.schema-generation.action" value="drop-and-create"/>
<property name="jakarta.persistence.schema-generation.scripts.create-target" value="database-and-scripts"/>
<property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306;create=true"/>
<property name="jakarta.persistence.jdbc.user" value="root"/>
<property name="jakarta.persistence.jdbc.password" value="myPwd"/>
</properties>
</persistence-unit>
</persistence>
The Entity is(getters and setters omitted):
#Entity
#NamedQuery(name = "ValueBeen.selectTable", query = "select u from ValueBeen u")
public class ValueBeen
{
public ValueBeen(){
}
public ValueBeen(String value)
{
this.value = value;
}
public ValueBeen(int id, String value)
{
this.id = id;
this.value = value;
}
#Id
#GeneratedValue
private int id;
#NotNull
private String value;
...
}
And the WebServlet who perform persistency is:
#WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
ValueBeen valueBeen=new ValueBeen("Hello");
//Manager persistence and manager been
EntityManagerFactory managerPersistence = Persistence.createEntityManagerFactory("GestoreDB");
EntityManager entityManager = managerPersistence.createEntityManager();
//Do persistence
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(valueBeen);
transaction.commit();
//close managers
entityManager.close();
managerPersistence.close();
}
}
I put the jdbc connector jar (Mysql connector 8.0.28) in .\glassfish-6.2.5\glassfish\domains\domain1\lib
As you deploy your app to glassfish container then "transaction-type" in persistence.xml i guess should be "JTA", and property "jakarta.persistence.jdbc.url" is invalid because you do not indicate any database / schema name after ":3306". Glassfish documentation provides instructions and examples how to setup global jdbc connections and those limited to only application scope.

Could not determine type for: javax.persistence.EntityManagerFactory, for columns: [org.hibernate.mapping.Column(emf)]

I work in Eclipse with Hibernate, JPA and postgres and I get following report
13:54:37,754 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 85) MSC000001: Failed to start service jboss.persistenceunit."NewPestsList-0.0.1-SNAPSHOT.war#tvTutorialPU": org.jboss.msc.service.StartException in service jboss.persistenceunit."NewPestsList-0.0.1-SNAPSHOT.war#tvTutorialPU": javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
at org.jboss.as.jpa#17.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:198)
at org.jboss.as.jpa#17.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:128)
at org.wildfly.security.elytron-private#1.9.1.Final//org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:649)
at org.jboss.as.jpa#17.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:212)
at org.jboss.threads#2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads#2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
at org.jboss.threads#2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
at org.jboss.threads#2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
at java.base/java.lang.Thread.run(Thread.java:830)
at org.jboss.threads#2.3.3.Final//org.jboss.threads.JBossThread.run(JBossThread.java:485)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
at org.hibernate#5.3.10.Final//org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1016)
at org.hibernate#5.3.10.Final//org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:942)
at org.hibernate.jipijapa-hibernate5-3#17.0.0.Final//org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.__build(TwoPhaseBootstrapImpl.java:44)
at org.hibernate.jipijapa-hibernate5-3#17.0.0.Final//org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:46002)
at org.jboss.as.jpa#17.0.0.Final//org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:170)
... 9 more
Caused by: org.hibernate.MappingException: Could not determine type for: javax.persistence.EntityManager, at table: smPests, for columns: [org.hibernate.mapping.Column(em)]
at org.hibernate#5.3.10.Final//org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:486)
at org.hibernate#5.3.10.Final//org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:453)
at org.hibernate#5.3.10.Final//org.hibernate.mapping.Property.isValid(Property.java:226)
at org.hibernate#5.3.10.Final//org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:624)
at org.hibernate#5.3.10.Final//org.hibernate.mapping.SingleTableSubclass.validate(SingleTableSubclass.java:54)
at org.hibernate#5.3.10.Final//org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:347)
at org.hibernate#5.3.10.Final//org.hibernate.boot.internal.SessionFactoryBuilderImpl.__build(SessionFactoryBuilderImpl.java:466)
at org.hibernate#5.3.10.Final//org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:40008)
at org.hibernate#5.3.10.Final//org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939)
... 12 more
13:54:37,755 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 2) WFLYCTL0013: Operation ("full-replace-deployment") failed - address: ([]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"NewPestsList-0.0.1-SNAPSHOT.war#tvTutorialPU\"" => "javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
Caused by: org.hibernate.MappingException: Could not determine type for: javax.persistence.EntityManager, at table: smPests, for columns: [org.hibernate.mapping.Column(em)]"}}
13:54:37,779 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) WFLYSRV0016: Replaced deployment "NewPestsList-0.0.1-SNAPSHOT.war" with deployment "NewPestsList-0.0.1-SNAPSHOT.war"
13:54:37,779 INFO [org.jboss.as.controller] (DeploymentScanner-threads - 2) WFLYCTL0183: Service status report
WFLYCTL0186: Services which failed to start: service jboss.persistenceunit."NewPestsList-0.0.1-SNAPSHOT.war#tvTutorialPU": javax.persistence.PersistenceException: [PersistenceUnit: tvTutorialPU] Unable to build Hibernate SessionFactory
My code is:
#Entity(name = "Smpests")
#Table(name = "smPests")
public class SmPests {      
#Id      
#GeneratedValue      
#Column(name = "id_pest")      
private int idPest;      
#Column(name = "latin")      
private String latinName;      
#OneToMany(targetEntity=SmPestsNames.class, mappedBy = "smpests", cascade = CascadeType.ALL, orphanRemoval = true)      
private List<SmPestsNames> smPestsNames;       
public int getIdPest() {            
return idPest;
}      
public void setIdPest(int idPest) {            
this.idPest = idPest;      
}      
public String getLatinName() {            
return latinName;      
}      
public void setLatinName(String latinName) { 
       this.latinName = latinName;      
}
public List<SmPestsNames> getSmPestsNames() {
      return smPestsNames;       
}
public void setSmPestsNames(List<SmPestsNames> smPestsNames) {     
        this.smPestsNames = smPestsNames;      
} 
#Entity
#Table(name = "smPestsNames")
public class SmPestsNames {      
#Column      
private Long idPestName;      
#Id      
#GeneratedValue      
#Column(name = "id")      
private Long idPest;      
#Column      
private int idLanguage;      
#Column      
private String name;             
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)      
private SmPests smpests;  
}
#Entity
#Model
public class SmPestsEdit extends SmPests {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("tvTutorialPU");
EntityManager em=emf.createEntityManager(); 
public void addButton() {        
     SmPests newPest = new SmPests();        
     newPest.setCode(getCode());          
   newPest.setLatinName(getLatinName());      
     SmPestsEdit repository = new SmPestsEdit();            
repository.createPest(newPest);  
}      
#Override      
public SmPests createPest(SmPests smPest)    {
    EntityManager em= emf.createEntityManager();        
    em.getTransaction().begin();       
    em.persist(smPest);         
    em.getTransaction().commit();        
    return smPest;      
}             
public SmPests readPest(int idPest)    {        
    EntityManager em= emf.createEntityManager();         
    em.getTransaction().begin();       
    SmPests smPest = em.find(SmPests.class, getIdPest());            
em.getTransaction().commit();       
    return smPest;      
} 
my persistence.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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_2.xsd"
version="2.2">
<persistence-unit name="tvTutorialPU"
transaction-type="JTA">
<jta-data-source>java:jboss/datasources/tvTutorial</jta-data-source>
<class>si.david.SmPests</class>
<class>si.david.SmPestsNames</class>
</persistence-unit>
</persistence>
I am fairly new at this so if I need to post anything else, please tell and i will add
Update:
Now I put EntityManagerFactory emf and EntityManager em in:
public SmPests createPest(SmPests smPest) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("tvTutorialPU");
EntityManager em= emf.createEntityManager();
em.getTransaction().begin();
em.persist(smPest);
em.getTransaction().commit();
return smPest;
}
Now I get error:
Target Unreachable, identifier 'smPestsEdit' resolved to null
Your problem is here:
#Entity
#Model
public class SmPestsEdit extends SmPests {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("tvTutorialPU");
EntityManager em=emf.createEntityManager();
// ...
}
Hibernate treats EntityManagerFactory emf and EntityManager em as fields which belong to the entity SmPestsEdit. It is a bad practice to put the code related to the work with EntityManager into the entity declaration. This code should be allocated in repositories.

javax.ejb.CreateException: Could not create stateless EJB with glassfish and boneCP on intellij-idea

I recently began to use Glassfish and boneCP on intellij idea with a simple web app, but there's a bug I can't understand. I believe I followed all the steps in the tutorial.
My model goes like this
#Entity
public class Song implements Serializable {
#Id
private String id;
private String title;
private LocalDate lastPlayed;
private int playCount;
public Song() {
title = "Chant sans titre";
id = generateId(title);
lastPlayed = LocalDate.ofEpochDay(0);
playCount = 0;
}
The EJB
#Stateless
public class SongDAO {
#PersistenceUnit(unitName = "statisthira_song")
private EntityManager em;
public void create(Song song){
try {
em.persist(song); } catch (Exception e) { e.printStackTrace(); }
}
the Servlet
#WebServlet(urlPatterns = "/new-song")
public class NewSongActionBean extends HttpServlet {
#EJB
SongDAO dao;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Song song = new Song();
song.setTitle("This is not a Test - Toby Mac");
song.setId(song.generateId(song.getTitle()));
dao.create(song);
this.getServletContext().getRequestDispatcher("/WEB-INF/newsong.jsp").forward(request, response);
}
}
My persistence.xml file under META-INF
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"
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="statisthira_song" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/bonecp_resource</jta-data-source>
<class>statis.hira.model.Song</class>
</persistence-unit>
</persistence>
the server runs without any problem, and when I check the jdbc connection pool with a ping, it succeeds. But when I try to access the url "/new-song", I get this error message
HTTP Status 500 - Internal Server Error
type Exception report
message Internal Server Error
description The server encountered an internal error that prevented it from fulfilling this request.
exception javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
here's a sample of the stacktrace
javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:435)
at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2579)
at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1971)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:210)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy194.create(Unknown Source)
at statis.hira.dao.__EJB31_Generated__SongDAO__Intf____Bean__.create(Unknown Source)
at statis.hira.servlets.NewSongActionBean.doGet(NewSongActionBean.java:26)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:700)
at com.sun.ejb.containers.util.pool.NonBlockingPool.getObject(NonBlockingPool.java:246)
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:430)
... 37 more
Caused by: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:514)
at com.sun.ejb.containers.StatelessSessionContainer.access$000(StatelessSessionContainer.java:97)
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:698)
... 39 more
Caused by: java.lang.IllegalStateException: Exception attempting to inject Env-Prop: statis.hira.dao.SongDAO/em#Field-Injectable Resource. Class name = statis.hira.dao.SongDAO Field name=em#java.lang.String### into class statis.hira.dao.SongDAO: Can not set javax.persistence.EntityManager field statis.hira.dao.SongDAO.em to com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper
at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:175)
at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:46)
at org.jboss.weld.injection.producer.DefaultInjector.inject(DefaultInjector.java:73)
at org.jboss.weld.injection.producer.StatelessSessionBeanInjector.inject(StatelessSessionBeanInjector.java:60)
at org.jboss.weld.injection.producer.ejb.SessionBeanInjectionTarget.inject(SessionBeanInjectionTarget.java:140)
at org.glassfish.weld.services.JCDIServiceImpl.injectEJBInstance(JCDIServiceImpl.java:257)
at com.sun.ejb.containers.BaseContainer.injectEjbInstance(BaseContainer.java:1748)
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:475)
... 41 more
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Env-Prop: statis.hira.dao.SongDAO/em#Field-Injectable Resource. Class name = statis.hira.dao.SongDAO Field name=em#java.lang.String### into class statis.hira.dao.SongDAO: Can not set javax.persistence.EntityManager field statis.hira.dao.SongDAO.em to com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:740)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:507)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:170)
at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:165)
... 48 more
Caused by: java.lang.IllegalArgumentException: Can not set javax.persistence.EntityManager field statis.hira.dao.SongDAO.em to com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
at java.lang.reflect.Field.set(Field.java:764)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:688)
... 51 more
You should change from
#PersistenceUnit(unitName = "statisthira_song")
to
#PersistenceContext(name= "statisthira_song")
#PersistenceUnit is used to inject EntityManagerFactory and #PersistenceContext is used to inject EntityManager

Eclipselink: No suitable driver found in glassfish while it works in JavaSE

I'm trying to create EntityManager in my webapp, but it's failing with:
No suitable driver found for jdbc:postgresql:://localhost/database
However the same persistance unit and the same code for creating EntityManager works when I run it as JavaSE console application (from main() ).
Googling gave me several common problems causing that error:
JDBC url is wrong
Shouldn't be since it works from main
JDBC Driver is not in the class path
I can create a Class object using Class.forName("org.postgresql.Driver"); for the driver so I think it is in the classpath.
Other things I tried:
I thought maybe the driver jar from glassfish/lib and the webapp/WEB-INF/lib are conflicting somehow so I tried with both of them together and separately, no luck.
Recreated a small new webapp hoping the problem will go away, it didn't :-)
Inject #PersistanceUnit - also didn't work, don't know is it the same issue or I didn't use it properly as I'm still learning about injection and EJBs
Thanks
Full error:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost/database Error Code: 0
Here is the code:
ManagedBean in webapp:
#ManagedBean
public class TestBean {
private String entry;
private String driver;
public String getFromDatabase(){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Unit1");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
EntityOne one = new EntityOne();
one.id = 1;
one.entry = "Bla bla";
em.persist(one);
tx.commit();
em.close();
return "done";
}
public String createDriver(){
try {
Class d = Class.forName("org.postgresql.Driver");
driver = d.getName();
} catch (ClassNotFoundException e) {
driver = "Class not found";
return "";
}
return "";
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getEntry() {
return entry;
}
public void setEntry(String entry) {
this.entry = entry;
}
}
Same code working in main:
public class Standalone {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Unit1");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
EntityOne one = new EntityOne();
one.id = 1;
one.entry = "Bla bla";
em.persist(one);
tx.commit();
em.close();
}
}
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="Unit1" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.test.EntityOne</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost/database"/>
<property name="javax.persistence.jdbc.user" value="darko"/>
<property name="javax.persistence.jdbc.password" value="sifra"/>
<property name="eclipselink.target-database" value="PostgreSQL"/>
</properties>
</persistence-unit>
Place the posgres jdbc driver into the lib of glassfish. Its something like this.
[glassfish_home]/glassfish/domains/YOUR_DOMAIN/lib/
Also, restart the server after this.

Simple local JPA2HBase App with DataNucleus

I want to build a minimalistic local app that reads/writes HBase via JPA2 without orm.xml and without maven2.
Thereby I use Eclipse with the DataNucleus Plugin whose Enhancer is enabled for the project.
Inspired by
http://matthiaswessendorf.wordpress.com/2010/03/17/apache-hadoop-hbase-plays-nice-with-jpa/
I got the following Entities:
#Entity
#Table(name="account_table")
public class Account
{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
String firstName = null;
String lastName = null;
int level = 0;
#Embedded
Login login = null;
public Account() { }
public Account(String firstName, String lastName, int level, Login login) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.level = level;
this.login = login;
}
and
#Embeddable
public class Login
{
private String login = null;
private String password = null;
public Login() {
// TODO Auto-generated constructor stub
}
public Login(String login, String password) {
super();
this.login = login;
this.password = password;
}
}
The src/META-INF/persistence.xml
<persistence
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
−
<persistence-unit name="hbase-addressbook"
transaction-type="RESOURCE_LOCAL">
<class>de.syrtec.jpa2hbase.entities.Login</class>
<class>de.syrtec.jpa2hbase.entities.Account</class>
<properties>
<property name="datanucleus.ConnectionURL" value="hbase" />
<property name="datanucleus.ConnectionUserName" value="" />
<property name="datanucleus.ConnectionPassword" value="" />
<property name="datanucleus.autoCreateSchema" value="true" />
<property name="datanucleus.validateTables" value="false" />
<property name="datanucleus.Optimistic" value="false" />
<property name="datanucleus.validateConstraints" value="false" />
</properties>
</persistence-unit>
</persistence>
the DAO:
public class TestDAO {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hbase-addressbook");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = null;
Account a1 = new Account("myPre", "mySur", 1, new Login("a", "b"));
tx = em.getTransaction();
tx.begin();
em.persist(a1);
tx.commit();
}
}
But when first line of the test DAO is executed...
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hbase-addressbook");
..I get:
11/09/01 06:57:05 INFO DataNucleus.MetaData: Class "de.syrtec.jpa2hbase.entities.Account" has been specified with JPA annotations so using those.
11/09/01 06:57:05 INFO DataNucleus.MetaData: Class "de.syrtec.jpa2hbase.entities.Login" has been specified with JPA annotations so using those.
Exception in thread "main" javax.persistence.PersistenceException: Explicit persistence provider error(s) occurred for "hbase-addressbook" after trying the following discovered implementations: org.datanucleus.api.jpa.PersistenceProviderImpl from provider: org.datanucleus.api.jpa.PersistenceProviderImpl
at javax.persistence.Persistence.createPersistenceException(Persistence.java:242)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:184)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:70)
at de.syrtec.jpa2hbase.start.TestDAO.main(TestDAO.java:15)
Caused by: org.datanucleus.exceptions.NucleusUserException: Errors were encountered when loading the MetaData for the persistence-unit "hbase-addressbook". See the nested exceptions for details
at org.datanucleus.metadata.MetaDataManager.loadPersistenceUnit(MetaDataManager.java:879)
at org.datanucleus.api.jpa.JPAEntityManagerFactory.initialiseNucleusContext(JPAEntityManagerFactory.java:745)
at org.datanucleus.api.jpa.JPAEntityManagerFactory.<init>(JPAEntityManagerFactory.java:422)
at org.datanucleus.api.jpa.PersistenceProviderImpl.createEntityManagerFactory(PersistenceProviderImpl.java:91)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:150)
... 2 more
Caused by: org.datanucleus.exceptions.ClassNotResolvedException: Class "−
de.syrtec.jpa2hbase.entities.Login" was not found in the CLASSPATH. Please check your specification and your CLASSPATH.
at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:247)
at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:412)
at org.datanucleus.metadata.MetaDataManager.loadPersistenceUnit(MetaDataManager.java:859)
... 6 more
Before I ran the DAO I triggered class enhancing by datanucleus succesfully:
DataNucleus Enhancer (version 3.0.0.release) : Enhancement of classes
DataNucleus Enhancer completed with success for 2 classes. Timings : input=623 ms, enhance=101 ms, total=724 ms. Consult the log for full details
Although I don't understand that enhancing isn't triggered automatically (referring to the logs) despite of having auto-enhancement for the project activated..
Does anybody know why my entities aren't found?
And that minus sign in persistence.xml ?