I'm attempting to create a JUnit test for my DAO object. The JUnit is ran directly from Netbeans. I'm quite new to several of these technologies, and as a result I'm having a heck of a time tracing down where my errors are coming from. My code and the corresponding error that I'm seeing are:
Jul 22, 2011 7:09:09 PM
com.sun.enterprise.v3.server.CommonClassLoaderServiceImpl
findDerbyClient INFO: Cannot find javadb client jar file, derby jdbc
driver will not be available by default. FATAL
[DatasourceConnectionProvider] - Could not find datasource: Waylon
org.omg.CORBA.COMM_FAILURE: FINE: IOP00410001: Connection failure:
socketType: IIOP_CLEAR_TEXT; hostname: localhost; port: 3700 vmcid:
OMG minor code: 1 completed: No javax.naming.NamingException: Lookup
failed for 'Waylon' in
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl}
[Root exception is javax.naming.NamingException: Unable to acquire
SerialContextProvider for
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl}
[Root exception is org.omg.CORBA.COMM_FAILURE: FINE: IOP00410001:
Connection failure: socketType: IIOP_CLEAR_TEXT; hostname: localhost;
port: 3700 vmcid: OMG minor code: 1 completed: No]] at
sun.reflect.GeneratedConstructorAccessor31.newInstance(Unknown Source)
at
com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at
com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at javax.naming.InitialContext.lookup(InitialContext.java:392) at
com.sun.corba.ee.spi.orbutil.logex.corba.CorbaExtension.makeException(CorbaExtension.java:248)
at
com.sun.corba.ee.spi.orbutil.logex.corba.CorbaExtension.makeException(CorbaExtension.java:95)
at
org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:52)
at
com.sun.corba.ee.spi.orbutil.logex.WrapperGenerator.handleFullLogging(WrapperGenerator.java:387)
at
org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124)
at
com.sun.corba.ee.spi.orbutil.logex.WrapperGenerator.access$400(WrapperGenerator.java:107)
at
org.hibernate.ejb.InjectionSettingsFactory.createConnectionProvider(InjectionSettingsFactory.java:29)
at
com.sun.corba.ee.spi.orbutil.logex.WrapperGenerator$2.invoke(WrapperGenerator.java:511)
at
org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:62)
at
com.sun.corba.ee.spi.orbutil.proxy.CompositeInvocationHandlerImpl.invoke(CompositeInvocationHandlerImpl.java:99)
at
org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
at $Proxy40.connectFailure(Unknown Source) at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
at
com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImpl.(SocketOrChannelConnectionImpl.java:257)
at
org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at
com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImpl.(SocketOrChannelConnectionImpl.java:270)
at
org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
at
com.sun.corba.ee.impl.transport.SocketOrChannelContactInfoImpl.createConnection(SocketOrChannelContactInfoImpl.java:129)
at
com.sun.corba.ee.impl.protocol.CorbaClientRequestDispatcherImpl.beginRequest(CorbaClientRequestDispatcherImpl.java:223)
at
org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:126)
at
com.sun.corba.ee.impl.protocol.CorbaClientDelegateImpl.request(CorbaClientDelegateImpl.java:228)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at
com.sun.corba.ee.impl.protocol.CorbaClientDelegateImpl.is_a(CorbaClientDelegateImpl.java:393)
at org.omg.CORBA.portable.ObjectImpl._is_a(ObjectImpl.java:112) at
javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at
org.omg.CosNaming.NamingContextHelper.narrow(NamingContextHelper.java:69)
at
com.google.inject.persist.jpa.JpaPersistService.start(JpaPersistService.java:94)
at
com.sun.enterprise.naming.impl.SerialContext$ProviderCacheKey.getNameService(SerialContext.java:1241)
at waylon.label.LabelDAOIJTest.setUpClass(LabelDAOIJTest.java:36) at
com.sun.enterprise.naming.impl.SerialContext.getRemoteProvider(SerialContext.java:411)
at
com.sun.enterprise.naming.impl.SerialContext.getProvider(SerialContext.java:347)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:504)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at javax.naming.InitialContext.lookup(InitialContext.java:392) at
java.lang.reflect.Method.invoke(Method.java:597) at
org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:52)
at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at
org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at
org.hibernate.ejb.InjectionSettingsFactory.createConnectionProvider(InjectionSettingsFactory.java:29)
at
org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:62)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at
org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
at
org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at
org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at org.junit.runners.ParentRunner.run(ParentRunner.java:303) at
org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
at junit.framework.JUnit4TestAdapter.run(JUnit4TestAdapter.java:39)
at
org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:126)
at
org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:518)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at
org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1052)
at
org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:906)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at
com.google.inject.persist.jpa.JpaPersistService.start(JpaPersistService.java:94)
at waylon.label.LabelDAOIJTest.setUpClass(LabelDAOIJTest.java:36)
Caused by: javax.naming.NamingException: Unable to acquire
SerialContextProvider for
SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.url.pkgs=com.sun.enterprise.naming,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl}
[Root exception is org.omg.CORBA.COMM_FAILURE: FINE: IOP00410001:
Connection failure: socketType: IIOP_CLEAR_TEXT; hostname: localhost;
port: 3700 vmcid: OMG minor code: 1 completed: No] at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
com.sun.enterprise.naming.impl.SerialContext.getProvider(SerialContext.java:352)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:504)
... 29 more at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
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="WaylonPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>Waylon</jta-data-source>
<class>waylon.label.Label</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
My DAO under Test:
package waylon.label.impl;
import com.google.inject.Inject;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import waylon.label.Label;
import waylon.label.LabelDAO;
/**
* {#inheritDoc}
*/
public class LabelDAOImpl implements LabelDAO {
private final EntityManager em;
#Inject
public LabelDAOImpl( EntityManager em ) {
this.em = em;
}
/**
* {#inheritDoc}
*/
#Override
public List<Label> getAllLabels() throws Exception {
TypedQuery<Label> typedQuery = em.createQuery(
"SELECT * from LABEL", Label.class );
return typedQuery.getResultList();
}
/**
* {#inheritDoc}
*/
#Override
public Label createLabel(String name) throws Exception {
em.getTransaction().begin();
Label label = new Label();
label.setName( name );
em.persist( label );
em.getTransaction().commit();
return label;
}
/**
* {#inheritDoc}
*/
#Override
public void removeLabel(String name) throws Exception {
Label label = getLabel( name );
removeLabel( label );
}
/**
* {#inheritDoc}
*/
#Override
public Label getLabel(String name) throws Exception {
Label label = em.find( Label.class, name );
return label;
}
/**
* {#inheritDoc}
*/
#Override
public void removeLabel(Label label) throws Exception {
if ( null != label ) {
em.getTransaction().begin();
em.remove( label );
em.getTransaction().commit();
}
}
}
My JUnit Test:
package waylon.label;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.jpa.JpaPersistModule;
import java.util.List;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import org.hamcrest.core.IsEqual;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import waylon.label.impl.LabelDAOModule;
/**
* A JUnit Test to test our database connection and JPA code.
* #author Benjamin Bays
*/
public class LabelDAOIJTest {
private LabelDAO objectInTest = null;
private static final String PUNIT = "WaylonPU";
private static Injector injector = null;
private static PersistService persistService = null;
#BeforeClass
public static void setUpClass() throws Exception {
injector = Guice.createInjector(
new JpaPersistModule(PUNIT),
new LabelDAOModule() );
persistService = injector.getInstance( PersistService.class );
persistService.start();
}
#AfterClass
public static void tearDownClass() throws Exception {
persistService.stop();
}
#Before
public void setUp() {
objectInTest = injector.getInstance( LabelDAO.class );
}
#Test
public void doEverything() throws Exception {
final String testName = "Test Label";
Label label1 = objectInTest.createLabel( testName );
assertThat( label1.getName(), IsEqual.equalTo( testName ) );
Label label2 = objectInTest.getLabel(testName);
assertThat( label2.getName(), IsEqual.equalTo( testName ) );
final String testName3 = "Test Label3";
Label label3 = objectInTest.createLabel( testName3 );
assertThat( label3.getName(), IsEqual.equalTo( testName3 ) );
List<Label> allLabels = objectInTest.getAllLabels();
assertThat( allLabels, hasItems( label1, label3 ) );
objectInTest.removeLabel( label1 );
objectInTest.removeLabel( testName3 );
List<Label> noLabels = objectInTest.getAllLabels();
assertThat( noLabels.size(), IsEqual.equalTo( 0 ) );
}
}
Any help would be greatly appreciated. Thanks.
This took a long time to figure out. I think the overall lesson here is to learn only one new technology at a time. I've provided the series of steps I took to get my JUnits to run, but overall it was several mistakes that were resolved by RTFM.
To give credit where it is due, these resources helped tremendously.
http://blogs.oracle.com/geertjan/entry/embedded_database_for_netbeans_platform
http://platform.netbeans.org/tutorials/nbm-crud.html
Eclipslink - Unknown entity type
I started by recreating my database service using the first resource. This involved recreating each table and reestablishing the foreign key dependencies (annoying, but necessary).
I then followed the second tutorial to have netbeans automatically generate an Entity from my database table. My entity required no changes, but this did cause Netbeans to generate a persistence.xml. I compared it against my own, and came up with with this segment:
<?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="LabelDAOIJTest" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>waylon.label.Label</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby:Waylon;create=true"/>
<property name="javax.persistence.jdbc.password" value="app"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="javax.persistence.jdbc.user" value="app"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>
The big changes here are:
The change in
The change in connection string (this is to point to the in memory DB I setup).
Setting the ddl-generation property to "drop-and-create-tables".
Finally, my unit test ran, hooray! Just to round things out, there were errors in my production code (because I'm a total beginner at JPA). The changes I made were to LabelDAOImpl.java. I learned that SELECT * doesn't work in JPA :)
/**
* {#inheritDoc}
*/
#Override
public List<Label> getAllLabels() throws Exception {
TypedQuery<Label> typedQuery = em.createQuery(
"SELECT x FROM Label x", Label.class );
return typedQuery.getResultList();
}
If you are using spring, Make sure you have your application context resolved properly. Like activate appropriate spring profile for the test.
That worked for me
Related
When I try to connect to the db I get a 500 error and closes my eclipse/tomcat. Does anyone know how could I fix it?
Confirm Servlet
package be.pxl.tafelboeker.servlets;
import be.pxl.tafelboeker.dao.BoekingDAO;
import be.pxl.tafelboeker.domain.Boeking;
import be.pxl.tafelboeker.services.BoekingService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
#WebServlet(value = "/Confirm", initParams = {
#WebInitParam(name = "ConfirmPage",
value = "/confirm.jsp") })
public class ConfirmServlet extends HttpServlet {
private String ConfirmPage;
private String geluktPage;
private String misluktPage;
private BoekingService service = new BoekingService();
#Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
ConfirmPage = getInitParameter("ConfirmPage");
geluktPage ="gelukt.jsp";
misluktPage = "mislukt.jsp";
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Boeking bean = new Boeking();
HttpSession sess = request.getSession();
bean = (Boeking)sess.getAttribute("bean");
request.setAttribute("bean", bean);
request.getRequestDispatcher(ConfirmPage).forward(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO STUDENT : boek tafel, toon gelukt.jsp indien de boeking gelukt is en toon mislukt.jsp indien de tafel niet geboekt kan worden
Boeking bean = new Boeking();
HttpSession sess = request.getSession();
bean = (Boeking)sess.getAttribute("bean");
BoekingDAO dao = new BoekingDAO("jdbc:mysql://localhost/survey", "root", "");
BoekingService serv = new BoekingService();
serv.setDao(dao);
if (serv.boekTafel(bean)) {
request.getRequestDispatcher(geluktPage).include(request,response);
} else {
request.getRequestDispatcher(misluktPage).include(request,response);
}
//Krijg een error bij het aanroepen van mijn Persistence krijg deze pas vandaag als ik mijn oefeningen van gister wil openen die werkte krijg ik het nu ook
//Dit is zeer vervelend. Kan nu niet testen of mijn query en de rest wel klopt.
//Heb mijn best gedaan om het zo goed mogelijk in te zullen
//Hetzelfde geld voor overzichtservlet & overzicht.jsp die ook dezelfde fout krijgen
}
}
Boeking Dao
package be.pxl.tafelboeker.dao;
import be.pxl.tafelboeker.domain.Boeking;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class BoekingDAO {
private String url;
private String user;
private String password;
EntityManagerFactory emf;
public BoekingDAO(String url, String user, String password) {
this.url = url;
this.user = user;
this.password = password;
}
public void setDriver(String driver)
throws ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
}
private EntityManager getEntityManager() {
emf = Persistence.createEntityManagerFactory("booking");
EntityManager em = emf.createEntityManager();
return em;
}
// TIP : Gebruik TemporalType.DATE voor je query parameter
public boolean isTafelBeschikbaar(LocalDate dag, int uur) {
EntityManager em = getEntityManager();
Query q1 = em.createQuery("select b from booking as b where (b.dag=?1 AND b.uur =?2) ");
q1.setParameter(1, dag);
q1.setParameter(2, uur);
if (q1.getMaxResults() == 0) {
return true;
} else {
return false;
}
}
public void boekTafel(Boeking bean) {
EntityManager em = getEntityManager();
em.persist(bean);
em.close();
emf.close();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
DriverLoader
package be.pxl.tafelboeker.dao;
public class DriverLoader {
static{
System.out.print("loading database");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("nope");
e.printStackTrace();
}
}
}
Boeking Service
package be.pxl.tafelboeker.services;
import be.pxl.tafelboeker.dao.BoekingDAO;
import be.pxl.tafelboeker.domain.Boeking;
import java.time.LocalDate;
import java.util.Date;
public class BoekingService {
private BoekingDAO dao;
public BoekingService(){
}
public BoekingDAO getDao() {
return dao;
}
public void setDao(BoekingDAO dao) {
this.dao = dao;
}
private boolean isTafelBeschikbaar(LocalDate dag, int uur){
return dao.isTafelBeschikbaar(dag, uur) ;
}
public boolean boekTafel(Boeking boeking){
LocalDate dag = boeking.getDag();
int uur = boeking.getUur();
if(isTafelBeschikbaar(dag, uur)){
dao.boekTafel(boeking);
return true;
}
return false;
}
}
pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>be.pxl</groupId>
<artifactId>HerexamensOef</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>HerexamensOef Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>HerexamensOef</finalName>
</build>
</project>
persistance
<?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_1.xsd"
version="2.1">
<persistence-unit name="booking" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/booking" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.schema-generation.database.action"
value="none" />
<!-- Hibernate specific -->
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
Error
HTTP Status 500 - Servlet execution threw an exception
type Exception report
message Servlet execution threw an exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NoClassDefFoundError: javax/persistence/Persistence
be.pxl.tafelboeker.dao.BoekingDAO.getEntityManager(BoekingDAO.java:35)
be.pxl.tafelboeker.dao.BoekingDAO.isTafelBeschikbaar(BoekingDAO.java:43)
be.pxl.tafelboeker.services.BoekingService.isTafelBeschikbaar(BoekingService.java:28)
be.pxl.tafelboeker.services.BoekingService.boekTafel(BoekingService.java:34)
be.pxl.tafelboeker.servlets.ConfirmServlet.doPost(ConfirmServlet.java:59)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.33 logs.
SQL of booking
-- phpMyAdmin SQL Dump
-- version 4.4.10
-- http://www.phpmyadmin.net
--
-
- Host: localhost
-- Generation Time: Jun 03, 2016 at 06:50 PM
-- Server version: 5.5.42
-- PHP Version: 7.0.0
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `boekingdb`
--
-- --------------------------------------------------------
--
-- Table structure for table `BOOKING`
--
CREATE TABLE `BOOKING` (
`id` bigint(20) NOT NULL,
`DAY` date DEFAULT NULL,
`NAME` varchar(255) DEFAULT NULL,
`CITY` varchar(255) DEFAULT NULL,
`STREET` varchar(255) DEFAULT NULL,
`HOUR` int(11) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
--
-- Indexes for table `BOOKING`
--
ALTER TABLE `BOOKING`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `BOOKING`
--
ALTER TABLE `BOOKING`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
Your persistence file use the JPA schema for the 2.1 version :
<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_1.xsd"
version="2.1">
so you should use a matching hibernate version : min Hibernate 4.3.X.
I guess that you use Hibernate because of it in your persistence.xml
<property name="hibernate.show_sql" value="true" />
So if you want use JPA as interface, you should add this dependency in your pom.xml :
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.2.Final</version>
</dependency>
This dependency includes hibernate-jpa-2.1-api which contains the class javax.persistence.Persistence
else if you want to use Hibernate directly without JPA as interface, you could use this dependency (or + 4.3.X):
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.2.Final</version>
</dependency>
More details here : http://hibernate.org/orm/downloads/
You have to add the javax.persistence-api.jar as a dependency:
<!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
i have a frustrating problem with my servlet. This is very basic, i'm supposed to add a blog entry to my database table which has 3 columns (id, tittel(title), main(mainbody)). I can load from my database and display in my jsp file. However i can't persist the data to the database and i cant figure out why.
I use postgres as a database.
This is my "saveBlog"-method:
public void lagreBlogg(Blogg b){
EntityManager em = Persistence.createEntityManagerFactory("kimsBlogg").createEntityManager();
EntityTransaction transaction = em.getTransaction();
try {
transaction.begin();
em.persist(b);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
} finally {
em.close();
}
}
}
This is my entity class:
#Entity
#Table(schema = "blogg", name = "blogg")
public class Blogg {
#Id
#GeneratedValue
private int id;
private String tittel;
private String main;
public Blogg() {
}
public Blogg(String tittel, String main){
this.tittel= tittel;
this.main = main;
}
public String getTittel() {
return tittel;
}
public void setTittel(String tittel) {
this.tittel = tittel;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
}
My persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="kimsBlogg">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>no.kim.model.Blogg</class>
<properties>
<property name="javax.persistence.jdbc.logging.level" value="INFO" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres" />
<property name="javax.persistence.jdbc.user" value="postgres" />
<property name="javax.persistence.jdbc.password" value="krheggen" />
<property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
</properties>
</persistence-unit>
This is the error i get:
HTTP Status 500 - Can only perform operation while a transaction is active.
type Exception report
message Can only perform operation while a transaction is active.
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.openjpa.persistence.InvalidStateException: Can only perform operation while a transaction is active.
org.apache.openjpa.kernel.BrokerImpl.assertTransactionOperation(BrokerImpl.java:4732)
org.apache.openjpa.kernel.BrokerImpl.rollback(BrokerImpl.java:1543)
org.apache.openjpa.kernel.DelegatingBroker.rollback(DelegatingBroker.java:940)
org.apache.openjpa.persistence.EntityManagerImpl.rollback(EntityManagerImpl.java:598)
no.kim.helpers.BloggDAO.lagreBlogg(BloggDAO.java:37)
no.kim.Controller.BloggServlet.doPost(BloggServlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
StackTrace
Caused by: org.apache.openjpa.persistence.PersistenceException: ERROR: relation "blogg.openjpa_sequence_table" does not exist
Position: 28 {prepstmnt 166406485 SELECT SEQUENCE_VALUE FROM blogg.OPENJPA_SEQUENCE_TABLE WHERE ID = ? FOR UPDATE} [code=0, state=42P01]
at org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:5001)
at org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:4961)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:133)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:107)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:59)
at org.apache.openjpa.jdbc.kernel.AbstractJDBCSeq.next(AbstractJDBCSeq.java:63)
at org.apache.openjpa.util.ImplHelper.generateValue(ImplHelper.java:159)
at org.apache.openjpa.util.ImplHelper.generateFieldValue(ImplHelper.java:143)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.assignField(JDBCStoreManager.java:774)
at org.apache.openjpa.util.ApplicationIds.assign(ApplicationIds.java:492)
at org.apache.openjpa.util.ApplicationIds.assign(ApplicationIds.java:468)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.assignObjectId(JDBCStoreManager.java:758)
at org.apache.openjpa.kernel.DelegatingStoreManager.assignObjectId(DelegatingStoreManager.java:135)
at org.apache.openjpa.kernel.StateManagerImpl.assignObjectId(StateManagerImpl.java:595)
at org.apache.openjpa.kernel.StateManagerImpl.preFlush(StateManagerImpl.java:3051)
at org.apache.openjpa.kernel.PNewState.beforeFlush(PNewState.java:44)
at org.apache.openjpa.kernel.StateManagerImpl.beforeFlush(StateManagerImpl.java:1072)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2143)
at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:2103)
at org.apache.openjpa.kernel.BrokerImpl.beforeCompletion(BrokerImpl.java:2021)
at org.apache.openjpa.kernel.LocalManagedRuntime.commit(LocalManagedRuntime.java:81)
at org.apache.openjpa.kernel.BrokerImpl.commit(BrokerImpl.java:1526)
at org.apache.openjpa.kernel.DelegatingBroker.commit(DelegatingBroker.java:932)
at org.apache.openjpa.persistence.EntityManagerImpl.commit(EntityManagerImpl.java:569)
relation "blogg.openjpa_sequence_table" does not exist
This seems to be straightforward, just create a sequence for the table blogg, more information here.
The problem is your " transaction.rollback();" in the catch method. if commit fails with an exception the connection is not longer active.
I've an entity class something like:
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "exampleclass")
public class ExampleEntityClass implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "ID")
private Integer id;
#Column(name = "name")
private String name;
public ExampleEntityClass() {
}
public ExampleEntityClass(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
}
And in my persistence.xml file I've:
<?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="MyPersistentUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- List of Entity classes -->
<class>model.Pingpongstation</class>
<properties>
<!-- SQL dialect -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<!-- Create/update tables automatically using mapping metadata -->
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mydb?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<!-- Tell the JPA provider to, by default, create the table if it does not exist. -->
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
As far as I understand, this <property name="javax.persistence.schema-generation.database.action" value="create"/> will tell the JPA provider, in this case EclipseLink, when persisting an Object of type ExampleEntityClass to create the table if it does not exist.
It works fine until I delete the table and try another persist. In other words, Lets say I do:
entityManager.persist(object); // It will work
And then I manually delete the table exampleClass from my database and re-run:
entityManager.persist(object); // After deleting the table -> It will fail
Now it will generate an exception. If I restart my MySQL server and try again it will work. OR if I restart my application and try again it will also work.
Whys is this happening? Why do I need to restart my MySQL server/application in order to make it work again?
Here's a simple runnable to show this happening. Press Go! then manually delete the table and press again Go! and you should have the exception.
NewJFrame class (and use ExampleEntityClass from above)
import java.util.ArrayList;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Go!");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(151, 151, 151)
.addComponent(jButton1)
.addContainerGap(199, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(145, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(130, 130, 130))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
ExampleEntityClass exampleEntityClass1 = new ExampleEntityClass(1, "John");
ExampleEntityClass exampleEntityClass2 = new ExampleEntityClass(2, "Lewis");
ExampleEntityClass exampleEntityClass3 = new ExampleEntityClass(3, "Mark");
ExampleEntityClass exampleEntityClass4 = new ExampleEntityClass(4, "Mary");
ArrayList<ExampleEntityClass> list = new ArrayList<>();
list.add(exampleEntityClass4);
list.add(exampleEntityClass3);
list.add(exampleEntityClass2);
list.add(exampleEntityClass1);
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("TesePersistentUnit");
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
for (ExampleEntityClass exampleEntityClass : list) {
entityManager.persist(exampleEntityClass);
entityManager.flush();
entityManager.clear();
}
transaction.commit();
}
catch(Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
finally {
entityManager.close();
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
}
Heres' the stack trace from the exception:
[EL Warning]: 2014-10-02 06:10:20.707--UnitOfWork(172425385)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mydb.exampleclass' doesn't exist
Error Code: 1146
Call: INSERT INTO exampleclass (ID, name) VALUES (?, ?)
bind => [2 parameters bound]
Query: InsertObjectQuery(model.ExampleEntityClass#7cd72cd)
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mydb.exampleclass' doesn't exist
Error Code: 1146
Call: INSERT INTO exampleclass (ID, name) VALUES (?, ?)
bind => [2 parameters bound]
Query: InsertObjectQuery(model.ExampleEntityClass#7cd72cd)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:868)
at model.NewJFrame.jButton1ActionPerformed(NewJFrame.java:90)
at model.NewJFrame.access$000(NewJFrame.java:19)
at model.NewJFrame$1.actionPerformed(NewJFrame.java:44)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6527)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6292)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4883)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4705)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4705)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:719)
at java.awt.EventQueue$4.run(EventQueue.java:717)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mydb.exampleclass' doesn't exist
Error Code: 1146
Call: INSERT INTO exampleclass (ID, name) VALUES (?, ?)
bind => [2 parameters bound]
Query: InsertObjectQuery(model.ExampleEntityClass#7cd72cd)
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:331)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:900)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:962)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:631)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1991)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:298)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:377)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:165)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:180)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:489)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:301)
at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:798)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1793)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1775)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1726)
at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:226)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:125)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:4196)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1441)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithPreBuiltChangeSet(UnitOfWorkImpl.java:1587)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.writeChanges(RepeatableWriteUnitOfWork.java:452)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:863)
... 39 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mydb.exampleclass' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:890)
... 69 more
if I restart my application and try again it will also work.
That's expected behaviour. The persistence context will check (and possibly create) tables when it is initialized, which happens once when you start your application.
Why is this happening?
Performance.
It is a rather heavy process to start up the persistence context. You don't want to do this all the time.
You get much better query throughput if you don't have to check all the time what the database looks like. Think prepared statements, cached query SQL and so on.
Updating your database schema (such as dropping tables) is usually something that involves careful planning, not something you can just do while the application is running.
This is normal and expected. The table is not created when persist is called as you speculate, but once the EntityManagerFactory is created. This is why the table is re-created when you restart your application.
I'm using JPA 2.0, eclipselink 2.x and maven. This is 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="certifications" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/com/ni/ds_edata_soa_nontx</jta-data-source>
<class>com.ni.apps.engineering.certification.entities.NicdsCliCertificationStg</class>
<class>com.ni.apps.engineering.certification.entities.NicdsCliCertificationStgPK</class>
<class>com.ni.apps.engineering.certification.entities.NicdsCliUpMapping</class>
<properties>
<property name="javax.persistence.jdbc.password" value="ni"/>
<!--property name="javax.persistence.jdbc.user" value="NI"/-->
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
I have this AbstractFacade
public abstract class AbstractFacade {
#PersistenceUnit(unitName = "certifications")
private static EntityManagerFactory emf;
private EntityManager em;
/**
* Gets the entity manager
* #return
*/
protected EntityManager getEntityManager(){
if(emf == null){
emf = Persistence.createEntityManagerFactory("certifications");
}
if(em == null){
em = emf.createEntityManager();
}
return em;
}
}
And this is how I implement it
public class CertificationFacade extends AbstractFacade{
/**
* Gets the certifications for the paramenter upId
* #param upId the upId
* #return the certifications
* #throws CertificationException
*/
public List<NicdsCliCertificationStg> getCertificationsByUpId(String upId)
throws CertificationException {
String stringQuery = new StringBuilder(
"select c from NicdsCliCertificationStg c, NicdsCliUpMapping d where c.id.contactsId = d.contactsId and d.profileId =")
.append(upId).toString();
try {
TypedQuery<NicdsCliCertificationStg> query = getEntityManager().createQuery(stringQuery,
NicdsCliCertificationStg.class);
return query.getResultList();
} catch (Exception e) {
throw new CertificationException(
CertificationConstants.INTERNAL_ERROR_MESSAGE, e);
}
}
}
This is the DAO
public final class CertificationDAO {
private CertificationDAO(){}
/**
**Gets the certifications for the requested upId
* #param upId the upId
* #return the certifications
* #throws CertificationException
*/
public static Certifications getCertificationByUpId(String upId) throws CertificationException{
Certifications response = new Certifications();
List<NicdsCliCertificationStg> certifications = new CertificationFacade().getCertificationsByUpId(upId);
CertificationType newCertification = new CertificationType();
for(NicdsCliCertificationStg cert : certifications){
newCertification.setAlternateEmail(cert.getAlternateEmail());
newCertification.setCertificationName(cert.getId().getCertName());
newCertification.setContactId((int)cert.getId().getContactsId());
newCertification.setFirstName(cert.getFirstName());
newCertification.setLastName(cert.getLastName());
newCertification.setPrimaryEmail(cert.getPrimaryEmail());
newCertification.setStatus(cert.getCertStatus());
response.getCertification().add(newCertification);
}
return response;
}
}
The exception is caused when I try to iterate through the list. I get a ClassCastException. I've been reading, and this is caused by 2 possible reasons: 1) the class is duplicated in the classpath (which is not so in my case) and 2) there are 2 different classloaders at the same time. This exception also happens when I redeploy the app to my weblogic. It seems that the garbage collector doesn't recycle the old classloader fast enough, and when I run the app, I'm dealing with two classloaders at the same time, causing the classcast exception. What I don't understand is that since I'm using JTA transaction type in my persistence.xml, the lifecycle of the EntityManagerFactory should be handled automatically. One option would be to close the factory myself, but I'm more interested in learning why isn't the JTA handling this for me. Thanks!
--EDIT--
Stacktrace
java.lang.ClassCastException: com.ni.apps.engineering.certification.entities.NicdsCliCertificationStg
at com.ni.apps.engineering.certification.dao.CertificationDAO.getCertificationByUpId(CertificationDAO.java:25)
at com.ni.apps.engineering.certification.rest.implementation.CertificationService.getCertificationByUpId(CertificationService.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1511)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1442)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1382)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:717)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:821)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:301)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:57)
at com.ni.apps.engineering.certification.filter.ConfigurableRepRestServletFilter.doFilter(ConfigurableRepRestServletFilter.java:139)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:57)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3730)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3696)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2273)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1490)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
So, this is how I fixed it.
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.ni.apps.engineering.certification.controller.AbstractFacade;
public class ApplicationListener implements ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent arg0) {
AbstractFacade.closeFactory();
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
}
}
That way, everytime I redeploy the app, I make sure that the factory that I've created is closed.
-Edit-
Just to make it clear, after creating that Listener class, I have to add the listener to the web.xml like this
<listener>
<listener-class>com.ni.apps.engineering.certification.filter.ApplicationListener</listener-class>
</listener>
The closeFactory() simply does emf.close() after verifying that emf is not null.
I've been trying to make a simple class in Java run with JPA to no avail. Help?
The title is the error I'm getting.
I've been trying to make a simple class in Java run with JPA to no avail. Help?
The title is the error I'm getting.
My persistence.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="geronimo" transaction-type="RESOURCE_LOCAL">
<provider>
org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>label.entities.Discography</class>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:sqlite:C:\\sqlitedb\\repo.db" />
<property name="openjpa.ConnectionDriverName" value="org.sqlite.JDBC" />
<property name="openjpa.ConnectionUserName" value="" />
<property name="openjpa.ConnectionPassword" value="" />
<property name="openjpa.Log" value="SQL=TRACE" />
</properties>
</persistence-unit>
My JPA class:
package label.implementations;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import label.entities.Discography;
public class Disconfigurator {
public static void main(String[] args) {
String persistenceUnit = "geronimo";
EntityManagerFactory eFactory = Persistence.createEntityManagerFactory(persistenceUnit);
EntityManager eManager = eFactory.createEntityManager();
EntityTransaction eTransaction = eManager.getTransaction();
eTransaction.begin();
Discography discography = new Discography();
discography.setArtist("Kings Of Leon");
discography.setSong("Radioactive");
eManager.persist(discography);
eTransaction.commit();
eManager.close();
eFactory.close();
}
}
My Entity class:
package label.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
#Entity(name="discography")
public class Discography {
#Column(name="artist",length=1000,nullable=true)
String artist;
#Column(name="song",length=1000,nullable=true)
String song;
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getSong() {
return song;
}
public void setSong(String song) {
this.song = song;
}
}
The error trace:
31 geronimo INFO [main] openjpa.Runtime - Starting OpenJPA 1.2.1
Exception in thread "main" <openjpa-1.2.1-r752877:753278 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: null
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:196)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:142)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:192)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:145)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:56)
at label.implementations.Disconfigurator.main(Disconfigurator.java:16)
Caused by: java.lang.NullPointerException
at org.sqlite.JDBC.connect(JDBC.java:63)
at org.apache.openjpa.jdbc.schema.SimpleDriverDataSource.getConnection(SimpleDriverDataSource.java:81)
at org.apache.openjpa.jdbc.schema.SimpleDriverDataSource.getConnection(SimpleDriverDataSource.java:60)
at org.apache.openjpa.lib.jdbc.DelegatingDataSource.getConnection(DelegatingDataSource.java:106)
at org.apache.openjpa.lib.jdbc.DecoratingDataSource.getConnection(DecoratingDataSource.java:87)
at org.apache.openjpa.jdbc.sql.DBDictionaryFactory.newDBDictionary(DBDictionaryFactory.java:91)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.getDBDictionaryInstance(JDBCConfigurationImpl.java:562)
at org.apache.openjpa.jdbc.meta.MappingRepository.endConfiguration(MappingRepository.java:1265)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:505)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:430)
at org.apache.openjpa.lib.conf.PluginValue.instantiate(PluginValue.java:103)
at org.apache.openjpa.conf.MetaDataRepositoryValue.instantiate(MetaDataRepositoryValue.java:68)
at org.apache.openjpa.lib.conf.ObjectValue.instantiate(ObjectValue.java:83)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.newMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:863)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.getMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:854)
at org.apache.openjpa.kernel.AbstractBrokerFactory.makeReadOnly(AbstractBrokerFactory.java:638)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:183)
... 5 more
You're trying to persist the Transaction and not your entity object.
This is what your code SHOULD look like --
EntityManagerFactory eFactory = Persistence.createEntityManagerFactory("geronimo");
EntityManager eManager = eFactory.createEntityManager();
EntityTransaction eTransaction = eManager.getTransaction();
//eManager.persist(eTransaction); <--- DO NOT DO THIS
eTransaction.begin();
Discography discography = new Discography();
discography.setArtist("Kings Of Leon");
discography.setSong("Radioactive");
eManager.persist(discography); // DO THIS INSTEAD. PERSIST THE ENTITY
eTransaction.commit();
eManager.close();
eFactory.close();