Initial SessionFactory creation failed.javax.persistence.PersistenceException - java

I am doing web application.I found many questions with same problem
Like this question
But I didn't get correct answer. My folder structure and class path everything is correct but why this Exception occurring really I don't know.
Below is my folder structure. Here persistence.xml file is within META-INF folder of src folder
My Persistance.xml:
<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_1_0.xsd"
version="1.0">
<persistence-unit name="jspWithJpa" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.entity.Student</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/reports" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
</properties>
</persistence-unit>
</persistence>
EntityManagerUtil
public class EntityManagerUtil {
private static final EntityManagerFactory emf;
static {
try {
emf = Persistence.createEntityManagerFactory("jspWithJpa");
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static EntityManagerFactory getEmf() {
return emf;
}
}
Exception Is:
Initial SessionFactory creation failed.javax.persistence.PersistenceException: No Persistence provider for EntityManager named jspWithJpa
Mar 2, 2014 11:16:08 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.action.InsertData] in context with path [/jspWithJpa] threw exception [Servlet execution threw an exception] with root cause
javax.persistence.PersistenceException: No Persistence provider for EntityManager named jspWithJpa

Change your provider tag to in persistence.xml to:
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
from your libs i can see that you're using eclipselink as JPA provider, not hibernate.

Related

JPA connect to Derby Database with Hibernate-ORM related problem in Quarkus

Currently, I am trying to build an API with JPA and Derby Database, and I've got some problems with Hibernate Reactive/Hibernate ORM.
Particularly, I want to connect to a Derby database server as follows:
QueryService.java:
#Transactional
#RequestScoped
public class QueryService implements Serializable {
#PersistenceContext
EntityManagerFactory emf;
private final static Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
public QueryService() {}
#PostConstruct
public void init() {
String urlDB = "my-persistence-unit";
emf = Persistence.createEntityManagerFactory(urlDB);
}
#PreDestroy
public void destroy() {
emf.close();
}
application.properties:
quarkus.hibernate-orm.database.generation=none
quarkus.datasource.db-kind=derby
quarkus.datasource.jdbc.url=jdbc:derby://localhost:1527/appDB;create=true
quarkus.datasource.jdbc.driver=org.apache.derby.jdbc.ClientDriver
quarkus.datasource.username=admin
quarkus.datasource.password=admin
quarkus.live-reload.instrumentation=true
In the persistence.xml file, I define a persistence unit to be used by the EntityManagerFactory in QueryService.java.
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
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">
<persistence-unit
name="my-persistence-unit"
transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/appDB;create=true"/>
<property name="hibernate.connection.username" value="admin"/>
<property name="hibernate.connection.password" value="admin"/>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
If I run this, I get this error: { "details": "Error id 07333181-bf2e-4640-8497-01de9bf6ccf7-1, java.lang.NullPointerException: Cannot invoke \"io.quarkus.hibernate.orm.runtime.recording.RecordedState.isReactive()\" because \"recordedState\" is null", "stack": "java.lang.NullPointerException: Cannot invoke \"io.quarkus.hibernate.orm.runtime.recording.RecordedState.isReactive()\" because \"recordedState\" is null\r\n\tat io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(FastBootHibernatePersistenceProvider.java:172)\r\n\tat io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.createEntityManagerFactory(FastBootHibernatePersistenceProvider.java:66)\r\n\tat javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:80)\r\n\tat javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)\r\n\tat app.QueryService.init(QueryService.java:29)\r\n\tat app.QueryService_Bean.create(Unknown Source)\r\n\tat app.QueryService_Bean.create(Unknown Source)\r\n\tat io.quarkus.arc.impl.RequestContext.getIfActive(RequestContext.java:74)\r\n\tat io.quarkus.arc.impl.ClientProxies.getDelegate(ClientProxies.java:30)\r\n\tat app.QueryService_ClientProxy.arc$delegate(Unknown Source)\r\n\tat app.QueryService_ClientProxy.obtainCourseList(Unknown Source)\r\n\tat app.Scolarite.obtainCourseList(Scolarite.java:49)\r\n\tat app.Scolarite_Subclass.obtainCourseList$$superforward1(Unknown Source)\r\n\tat app.Scolarite_Subclass$$function$$2.apply(Unknown Source)\r\n\tat io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:133)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:104)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.doIntercept(TransactionalInterceptorRequired.java:38)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:58)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.intercept(TransactionalInterceptorRequired.java:32)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired_Bean.intercept(Unknown Source)\r\n\tat io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:42)\r\n\tat io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)\r\n\tat io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:33)\r\n\tat app.Scolarite_Subclass.obtainCourseList(Unknown Source)\r\n\tat app.Scolarite_ClientProxy.obtainCourseList(Unknown Source)\r\n\tat app.ScolariteApplication.getCourseList(ScolariteApplication.java:22)\r\n\tat app.ScolariteApplication$quarkusrestinvoker$getCourseList_9c2e0d4fdac50820476d652c171e60223f72a1d5.invoke(Unknown Source)\r\n\tat org.jboss.resteasy.reactive.server.handlers.InvocationHandler.handle(InvocationHandler.java:29)\r\n\tat io.quarkus.resteasy.reactive.server.runtime.QuarkusResteasyReactiveRequestContext.invokeHandler(QuarkusResteasyReactiveRequestContext.java:114)\r\n\tat org.jboss.resteasy.reactive.common.core.AbstractResteasyReactiveContext.run(AbstractResteasyReactiveContext.java:145)\r\n\tat io.quarkus.vertx.core.runtime.VertxCoreRecorder$14.runWith(VertxCoreRecorder.java:576)\r\n\tat org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)\r\n\tat org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)\r\n\tat org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)\r\n\tat org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)\r\n\tat io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)" }
I tried to search for this on the internet, and it is said that this was because Hibernate Reactive and Hibernate Orm cannot be used together. But I don't know how to solve it. I am quite new to this. Could you please help me with it?

Glassfish 4 - TransactionRequiredException using Hibernate and CDI #Transactional

I am getting the following exception:
javax.el.ELException: javax.persistence.TransactionRequiredException
at com.sun.el.parser.AstValue.invoke(AstValue.java:279)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
Caused by: javax.persistence.TransactionRequiredException
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:161)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck(EntityManagerWrapper.java:151)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:299)
I am using Hibernate 4.3.5
#Named
#SessionScoped
public class MenuBean implements Serializable {
#PersistenceContext
private EntityManager entityManager;
#Transactional
public void create() {
MenuTitle menu = new MenuTitle();
menu.setLabel(label);
entityManager.persist(menu); //exception in this line
label = null;
}
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://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="MyPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>MySQL5</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.current_session_context_class" value="jta"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>
<property name="hibernate.hbm2ddl.auto" value="none"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
</properties>
</persistence-unit>
I have also tried to set hibernate.transaction.jta.platform to org.hibernate.engine.transaction.jta.platform.internal.SunOneJtaPlatform but it results in the same error.
EJB CMT´s are working fine.
The Create action is called from a commandButton:
<p:commandButton value="Create" process="#this type" update=":megaMenuForm:mainMenu" actionListener="#{menuBean.create()}" oncomplete="closeMenuDialog(xhr, status, args)"/>
See EJB specs if you want to manage transaction. Inject a resource UserTransaction.
Also #Transactional with not do anything here since you are using EJB.
In general you example should work, and #Transactional annotation will be just ignored. Could you try to make an interface, and call create method through it?
Looks like you are using EJB 2 style coding, but Glassfish 4 implements EJB 3.1, so it is better to go with a new one.

Hibernate: app doesn't close after crash

My app just creates an EntityManager and after that I throw a RuntimeException on purpose. If I place the RuntimeException line before I create the entity manager, the exception is correctly caught by main and the app closes (as expected). But if any exception occurs after that, the exception is caught (I can see the stacktrace) but the app keeps running and I have to kill it. In Netbeans, the thread's state is "zombie".
libs used
Hibernate 4.3.1 Final: all jars from jpa folder and required folder (link)
Database connector: jtds 1.3.1 (link)
My test class
package test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] args) {
// throw an exception here, app closes as expected
EntityManagerFactory factory = Persistence.createEntityManagerFactory("pu");
EntityManager em = factory.createEntityManager();
// throw an exception here, it runs forever
throw new RuntimeException();
}
}
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="pu" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
<property name="javax.persistence.jdbc.driver" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="user"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name="javax.persistence.jdbc.url" value="jdbc:jtds:sqlserver://server:1433/database"/>
</properties>
</persistence-unit>
</persistence>
Any EntityManagerFactory could get hold of critical resources which need proper cleanup; in your example it's probably a thread managing the connection.
You must make sure the factory is closed: normally frameworks take care of proper shutdown, but if you manage the resources yourself you have to enclose the next blocks in a finally block.
EntityManagerFactory factory = Persistence.createEntityManagerFactory("pu");
try {
// rest of your application here
}
finally {
factory.close();
}
Are you trying to close your application on purpose? I'm not sure I follow what you're attempting to do here.
If all you want to do is stop the application, you can call,
System.exit(0)
which signifies that the execution of the program was successful, or pass in other numbers to signify a failure.

An application using EJB 3.0 and Hibernate persistence provider gives an UnknownServiceException

I am trying to create a web app using JSF and EJB 3.0.
I am using plain JSF, Glassfish Server, Hibernate as my persistance provider. My database is apache derby.
Here my Stateless Session bean as follows:
#Stateless
#TransactionManagement(TransactionManagementType.CONTAINER)
public class StudentServiceBean implements StudentService{
#PersistenceContext(unitName="forPractise")
private EntityManager entityMgr;
#Resource
private SessionContext sessionContext;
#Override
public List<StudentVO> fetchStudentListOrderByStudentId(boolean flag){
List<StudentEntity> studentList = null;
TypedQuery<StudentEntity> studentQuery = null;
List<StudentVO> studentVOList = null;
String queryDesc = "select s from StudentEntity s order by s.studentId desc";
String query = "select s from StudentEntity s order by s.studentId";
try{
if(!flag){
studentQuery = entityMgr.createQuery(query,StudentEntity.class);
}else{
studentQuery = entityMgr.createQuery(queryDesc,StudentEntity.class);
}
studentList = studentQuery.getResultList();
studentVOList = new ArrayList<StudentVO>();
for(StudentEntity studentE : studentList){
studentVOList.add(new StudentVO(String.valueOf(studentE.getStudentId()),studentE.getStudentName(),studentE.getContactNumber()));
}
}catch(Exception e){
System.out.println(" EXCEPTION IN "+this.getClass().getName()+" in method fetchStudentListOrderByStudentId "+e);
}
return studentVOList;
}
And this is my persistence.xml:
<?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="forPractise" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/app</jta-data-source>
<class>com.entity.StudentEntity</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.SunONETransactionManagerLookup" />
</properties>
</persistence-unit>
</persistence>
What happens is on load of the JSP page, the getter method of StudentList is called -
inside the getter method I have written logic that if studentList is empty then call the studentService.fetchStudentListOrderByStudentId(true);.
But when I do this I get an exception:
EXCEPTION IN com.bb.StudentServiceBean in method
fetchStudentListOrderByStudentId
org.hibernate.service.UnknownServiceException: Unknown service
requested
[org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
Can you please tell me what I am missing, or where I am going wrong?
Thanks.
You indicate that you are using Hibernate 4.x, but the class you mentioned afaik is only valid for JPA 1.0 and Hibernate 3.x. Try removing the following line from your configuration:
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.SunONETransactionManagerLookup" />
Just in case it's of any interest, I got this error on Jetty when trying to start a Hibernate session:
Unknown service requested [org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
The root cause was a previous Exception (a few seconds earlier in the logs) which caused the spring context (WebAppContext) to fail to initialize.
Once I fixed the spring context, the "Unknown service requested" fixed itself. So, if you're seeing this error it's worth checking for earlier errors before investigating too much..

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