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.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
The UsersDAOImpl class is supposed to add a new user when I run the file as a JUnit test, but I keep getting a NullPointerException when I call sessionFactory.getCurrentSession() and I don't know why.
The session factory is put in the beans.xml.
The credentials to the database were removed for obvious reasons.
[beans.XML]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<!-- enable autowiring -->
<context:component-scan base-package="src"></context:component-scan>
<!-- enable #Transactional -->
<tx:annotation-driven />
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="username" value="{Master}"></property>
<property name="password" value="{password}"></property>
<property name="url" value="{url}"></property>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"></property>
<property name="packagesToScan" value="src"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory">
</property>
</bean>
<bean id="usersDAO" class="dao.UsersDAOImpl">
<property name="sessionFactory" ref="mySessionFactory"> </property>
</bean>
</beans>
[UsersDAOImpl.java]
package dao;
import static org.junit.Assert.*;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import customExceptions.*;
import util.Debug;
import util.HibernateUtil;
import domain.Users;
#Transactional
public class UsersDAOImpl implements UsersDAO {
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionfactory) {
this.sessionFactory = sessionfactory;
}
#Test
public void testPush() {
try {
push(new Users("username6", "email#gmail.com", "password", "firstName", "lastName", false));
} catch (UserNameTakenException e) {
e.printStackTrace();
fail();
} catch (InvalidNameException e) {
e.printStackTrace();
fail();
}
}
/**
* Adds a new user to the database
*
* #param newUser
* The user to be added
* #throws UserNameTakenException
* In the case a username is taken
* #throws InvalidNameException
* If a field is left blank, but front end should prevent that
*/
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void push(Users newUser) throws UserNameTakenException, InvalidNameException {
// For debugging purposes:
Debug.printMessage(this.getClass(), "push()", "invoked");
// Check if there are any empty Strings
if (newUser.getUsername().isEmpty() || newUser.getPassword().isEmpty() || newUser.getFirstName().isEmpty()
|| newUser.getLastName().isEmpty()) {
throw new InvalidNameException("There is an empty String");
}
// Get the session
//THIS IS WHERE I GET THE EXCEPTION
Session sess = sessionFactory.getCurrentSession();
// Check to see if the username is taken
Users users = getUserByName(newUser.getUsername());
// If the list is not empty, a user with the name was found
if (users != null) {
sess.close();
throw new UserNameTakenException("The username was found in the database");
} else {
// Otherwise, add the new user
// Debug
Debug.printMessage(this.getClass(), "push()", "username available.");
Debug.printErrorMessage(this.getClass(), "push()", "saving " + newUser.getUsername());
sess.save(newUser);
sess.close();
}
}
/**
* Updates the User's password in the database
*
* #param user
* The user to change
* #param newVal
* The new password
*/
#Override
public void updatePassword(Users user, String newVal) {
Debug.printMessage(this.getClass(), "updatePassword()", "invoked");
Session sess = HibernateUtil.getSession();
Transaction trans = sess.beginTransaction();
user.setPassword(newVal);
sess.update(user);
trans.commit();
sess.close();
}
/**
* Updates the User's first name in the database
*
* #param user
* The user to change
* #param newVal
* The new first name
*/
#Override
public void updateFirstName(Users user, String newVal) {
// For debugging purposes:
Debug.printMessage(this.getClass(), "updateFirstName()", "invoked");
Session sess = HibernateUtil.getSession();
Transaction trans = sess.beginTransaction();
user.setFirstName(newVal);
sess.update(user);
trans.commit();
sess.close();
}
/**
* Updates the User's last name in the database
*
* #param user
* The user to change
* #param newVal
* The new last name
*/
#Override
public void updateLastName(Users user, String newVal) {
// For debugging purposes:
Debug.printMessage(this.getClass(), "updateLastName()", "invoked");
Session sess = HibernateUtil.getSession();
Transaction trans = sess.beginTransaction();
user.setLastName(newVal);
sess.update(user);
trans.commit();
sess.close();
}
/**
* Returns the user with the given username
*
* #param username
* The username to find
*/
#Override
public Users getUserByName(String username) {
// For debugging purposes:
Debug.printMessage(this.getClass(), "getUserByName()", "invoked");
Session sess = HibernateUtil.getSession();
Users user = (Users) sess.get(Users.class, username);
sess.close();
return user;
}
/**
* Returns a list of all users from A_USERS
*/
#Override
public List<Users> getAllUsers() {
// For debugging purposes:
Debug.printMessage(this.getClass(), "getAllUsers()", "invoked");
Session sess = HibernateUtil.getSession();
Query query = sess.getNamedQuery("getAllUsers");
List<Users> users = query.list();
sess.close();
return users;
}
}
Also, I apologize if this is formatted incorrectly. This is my first time posting a question.
The Stack Trace
java.lang.NullPointerException
at dao.UsersDAOImpl.push(UsersDAOImpl.java:65)
at dao.UsersDAOImpl.testPush(UsersDAOImpl.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
null
The sessionFactory field is null.
As for why, I can only guess. You're both auto-wiring the sessionFactory field but also injecting it as a property via its configuration in the applicationContext.xml. Do one or the other, not both, and see what happens.
A session is opened whenever getCurrentSession() is called for the first time and closed when the transaction ends. This creates a brand new session if one does not exist or uses an existing one if one already exists. It automatically configured with both auto-flush and auto-close attributes as true means Session will be automatically flushed and closed.
We can use getCurrentSession() method when our transaction runs long time. To use this method we need to configure one property in hibernate.cfg.xml file. The property is
<propertyname="hibernate.current_session_context_class">thread</property>
Values for the current_session_context_class will be,
thread(local transaction)
managed jta(global transaction)
thread - session bound to a thread, for single thread execution if you call a getCurrentSession() then it will return you a same session object.
managed - this provided for managing session from some external entity, something like intercepter. maintaining session in a ThreadLocal same as a "thread" type, but having a different methods like bind(), unbind(), hasbind() to be used by external entity to maintain session in a context.
jta - session will be bound to a transaction, as we says a transaction then we need application server for using this context class.
public org.hibernate.classic.Session getCurrentSession() throws HibernateException {
if ( currentSessionContext == null ) {
throw new HibernateException( "No CurrentSessionContext configured!" );
}
return currentSessionContext.currentSession(); }
Or Try This
Session session = sessionFactory.getCurrentSession();
if (session.isOpen()) {
session.close();
}
TransactionSynchronizationManager.unbindResource(sessionFactory);
TransactionSynchronizationManager.clearSynchronization();
I'm new to JavaEE and currently learning JavaEE7. I have JavaEE7 installed and downloaded NetBeans 8.0.2 so I could follow allow with the Webinar published here:
https://www.youtube.com/watch?v=sCNslREYpD0&spfreload=10
This tutorial in the video uses JavaEE6 rather than JavaEE7.
I made it about 12 minutes into the Webinar before I encountered the java.lang.IllegalStateException mentioned in the title of my post. At 12:18 in the video, the presenter adds a #PersistenceUnit to the code, and then an EntityManagerFactory. Even though I have followed his tutorial very carefully, I'm having issues with persistence and keep getting the following Exception:
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null
at com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper.getDelegate(EntityManagerFactoryWrapper.java:103)
at com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper.createEntityManager(EntityManagerFactoryWrapper.java:114)
at org.glasssfish.samples.TestServlet.processRequest(TestServlet.java:79)
at org.glasssfish.samples.TestServlet.doGet(TestServlet.java:103)
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:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
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:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
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:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
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:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
I have search StackOverflow and Google extensively, and the answer I keep coming across relates to the location of the persistence.xml file. I'm using NetBeans which automatically creates and places the persistence.xml file in a Configuration Files folder.
The project layout in NetBean 8.0.2 looks like the following:
Web Pages
WEB-INF
index.html
Source Packages
org.glassfish.samples
TestServlet.java
org.glassfish.samples.model
Friend.java
Libraries
JDK 1.8 (Default)
GlassFish Server 4.1
Configuration Files
MANIFEST.MF
persistence.xml
Here is Friend.java file that was automatically generated by NetBeans as part of the tutorial:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.glasssfish.samples.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author james
*/
#Entity
#Table(name = "FRIEND")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Friend.findAll", query = "SELECT f FROM Friend f"),
#NamedQuery(name = "Friend.findByName", query = "SELECT f FROM Friend f WHERE f.name = :name"),
#NamedQuery(name = "Friend.findByAge", query = "SELECT f FROM Friend f WHERE f.age = :age")})
public class Friend implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 30)
#Column(name = "NAME")
private String name;
#Column(name = "AGE")
private Integer age;
public Friend() {
}
public Friend(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Override
public int hashCode() {
int hash = 0;
hash += (name != null ? name.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Friend)) {
return false;
}
Friend other = (Friend) object;
if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
return false;
}
return true;
}
#Override
public String toString() {
return "org.glasssfish.samples.model.Friend[ name=" + name + " ]";
}
}
Here is the TestServlet.java file:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.glasssfish.samples;
import java.io.IOException;
import java.io.PrintWriter;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.glasssfish.samples.model.Friend;
/**
*
* #author james
*/
#WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})
public class TestServlet extends HttpServlet {
#PersistenceUnit
EntityManagerFactory emf;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet TestServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
//
int count;
if (request.getSession().getAttribute("count") == null) {
count = 0;
} else {
count = (Integer)request.getSession().getAttribute("count");
}
request.getSession().setAttribute("count", ++count);
out.println("Accessed again: " + request.getSession().getAttribute("count"));
Friend f = (Friend)emf.createEntityManager().createNamedQuery("Friend.findAll").getResultList().get(0);
out.println("Friend name: " + f.getName());
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
And, of course, the seemingly infamous persistence.xml file that was automatically generated by NetBean 8.0.2:
<?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="JavaEE7WebinarPU" transaction-type="JTA">
<jta-data-source>jdbc/sample</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
I tried a variety of things like:
injecting a PersistenceContext instead of a PersistenceUnit and getting an EntityManager directly from there instead of using an EntityManagerFactor (not sure if I did that correctly).
modifying my #PersistenceUnit to #PersistenceUnit(unitName="JavaEE7WebinarPU"). This didn't help much. It just changed my error from:
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null
to
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName JavaEE7WebinarPU
I verified that my GlassFish server does, in fact, have a resource named jdbc/sample which is mapped to a pool named SamplePool. I also verified that my GlassFish server has a Connection pool named SamplePool. It is currently set as a javax.sql.DataSource resource type.
I was hoping someone with some more experience with JavaEE might be able to point out something obvious that I'm missing here. Or maybe something that has changed from JavaEE6 to JavaEE7 which may be the cause of my error.
Any help or suggestions would be greatly appreciated.
/
UPDATE: I just ran a Clean and Build in NetBeans and saw the following warning:
/
warning: Supported source version 'RELEASE_6' from annotation processor 'org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor' less than -source '1.8'`
I have JDK 1.8 installed (update 31), NetBeans 8.0.2, and GlassFish 4.1. Is this warning suggesting that eclipseLink won't work with JDK 1.8?
/
UPDATE #2: Ok, well this seems to be a very lame resolution. After trying to fix this for a couple of hours. I shut down my GlassFish server, Disconnected from my database, performed a 'Clean and Build', started everything back up again, and redeployed. Now everything seems to be working as I expect it to. I suppose something got a little wonky somewhere and only a 'clean' was able to resolve the issue. Ugh.
/
Apparently something in my build got a little funky. I shut down all my servers, did a Clean and Build and redeployed. Now, everything seems to be working.
Thanks all for your suggestions.
What I found missing in your persistence.xml is the provider. In your persistence-unit element add the following tag also
<provider> provider_name</provider>
check which provider you are using
You have specified entity manager in your post and you trying to access entity manager both are different please see
You should do like this
#PersistenceContext(name="entiyManager")
EntityManager entitymanager;
Also you need to initialized your entitymanager factory
James, I think it is a simple solution.
change from
#PersistenceUnit
to
#PersistenceUnit(unitName="JavaEE7WebinarPU")
also see https://docs.oracle.com/javaee/6/api/javax/persistence/PersistenceUnit.html
No problem buddy its very easy just add this in persistence.xml file
<?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="JavaEE7WebinarPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/sample</jta-data-source>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
You have an option at persistence class generated by netbeans to name your persistence unit. After naming it just do a clean and build and you will get your answer.
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 trying create a generic class for automate the creation of jpacontainer in my project but doesn't work and returns some errors. The errors refer No EntityProvider has been set.
I'm trying this.
/** class init jpacontainer */
public class PersistJPAContainer<T> extends JPAContainer<T>{
private static final long serialVersionUID = 1L;
private static final String PERSISTENCE_UNITNAME = "ps_unitname";
public PersistJPAContainer(Class<T> entityClass) {
super(entityClass);
JPAContainer<?> container = JPAContainerFactory.make(entityClass, PERSISTENCE_UNITNAME);
}
}
/** my app UI */
public class AcademiaonlineUI extends UI {
private final JPAContainer<Empresa> datasource = new PersistJPAContainer<Empresa>(Empresa.class);
#Override
protected void init(VaadinRequest request) {
Table tabela = new Table("Empresa", datasource);
VerticalLayout vLayout = new VerticalLayout();
vLayout.addComponent(tabela);
setContent(vLayout);
}
}
/** errors */
Mar 17, 2014 11:14:30 AM com.vaadin.server.DefaultErrorHandler doDefault
SEVERE:
java.lang.IllegalStateException: No EntityProvider has been set
at com.vaadin.addon.jpacontainer.JPAContainer.doGetEntityProvider(JPAContainer.java:313)
at com.vaadin.addon.jpacontainer.JPAContainer.size(JPAContainer.java:912)
at com.vaadin.ui.AbstractSelect.size(AbstractSelect.java:762)
at com.vaadin.ui.Table.refreshRenderedCells(Table.java:1654)
at com.vaadin.ui.Table.attach(Table.java:4171)
at com.vaadin.server.AbstractClientConnector.attach(AbstractClientConnector.java:583)
at com.vaadin.ui.AbstractComponent.attach(AbstractComponent.java:572)
at com.vaadin.ui.AbstractComponent.setParent(AbstractComponent.java:479)
at com.vaadin.ui.AbstractSingleComponentContainer.setContent(AbstractSingleComponentContainer.java:137)
at com.vaadin.ui.UI.setContent(UI.java:1162)
at br.com.academiaonline.AcademiaonlineUI.init(AcademiaonlineUI.java:24)
at com.vaadin.ui.UI.doInit(UI.java:614)
at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:223)
at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:73)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1382)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:724)
//persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="ps_unitname" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>br.com.academiaonline.beans.Empresa</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:~/AODB"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value="master"/>
<!-- Cria a base de dados automaticamente -->
<property name="eclipselink.ddl-generation" value="create-or-extend-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<!-- Exibe log de erros no console do eclipse -->
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
Any idea ?
Try some thing like this in your Constructor
public class CustomJPA extends JPAContainer {
private static final long serialVersionUID = -1752491307148335890L;
private static final String PU_UNIT="ps_unitname";
public CustomJPA(Class<T> entityClass, String persitenceUnitName) {
super(entityClass);
EntityManager entityManager = JPAContainerFactory.createEntityManagerForPersistenceUnit(persitenceUnitName);
setEntityProvider(new CachingMutableLocalEntityProvider<T>(entityClass,entityManager));
}
public CustomJPA(Class<T> entityClass) {
super(entityClass);
EntityManager entityManager =JPAContainerFactory.createEntityManagerForPersistenceUnit(PU_UNIT);
setEntityProvider(new CachingMutableLocalEntityProvider<T>(entityClass,entityManager));
}
}
Where ever I have to initalise my Container, I do it some thing like this
JPAContainer<Bean> myBean= new CustomJPA<Bean>(Bean.class);
Hope this helps. I feel that you are writing some redundant code.
NOTE:
I have not tested this snippet of code.
Try to use appropriate class as your EnityProvider, I used the
default one in this example
BTW, is this what you are expecting??
now works...after some tests finally works.
I did so.
public class PersistJPAContainer<T> extends JPAContainer<T>{
private static final long serialVersionUID = 1L;
private static final String PERSISTENCE_UNITNAME = "ps_unitname";
public PersistJPAContainer(Class<T> entityClass) {
super(entityClass);
EntityManager em = JPAContainerFactory.createEntityManagerForPersistenceUnit(PERSISTENCE_UNITNAME);
setEntityProvider(new CachingMutableLocalEntityProvider<T>(entityClass, em));
}
}
public class AcademiaonlineUI extends UI {
private final PersistJPAContainer<Empresa> datasource = new PersistJPAContainer<Empresa>(Empresa.class);
And works !
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