Table/View does not exist in JavaEE web app deployed on Glassfish - jpa

I tried to deploy a JavaEE Web app with JPA persistence on a Glassfish server I installed on an Amazon EC2 instance. Everything worked fine for the deployment and for web pages rendering in my browser, but when I try to use persistence the result is the error "Table/View 'ATHLETE' does not exist'.
This is the first time I try to develop a web app with JPA and I'm trying to create a skeleton to use in the future for we app, but I think I'm missing a fundamental part. Also, using #GeneratedValue for the #Id I get a SEQUENCE table missing error. I'm afraid the two problems are related
The Athlete.java
package com.storassa.javaee.scuolesci;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
#Entity
#NamedQuery(name = "findAllAthletes", query = "SELECT b FROM Athlete b")
public class Athlete {
static int idRaw; // I use this to avoid the #GeneratedValue issue
#Id
int id;
String name, surname;
int birth;
public Athlete () {
idRaw++;
id = idRaw;
}
<getters and setters>
}
The AthleteEjb.java
package com.storassa.javaee.scuolesci;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Startup;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.annotation.sql.*;
#LocalBean
#Stateless
public class AthleteEJB {
#PersistenceContext(unitName="scuoleSciPU")
private EntityManager em;
public List<Athlete> findAthlete() {
Query query = em.createNamedQuery("findAllAthletes");
return query.getResultList();
}
public Athlete createAthlete(Athlete athlete) {
em.persist(athlete);
return athlete;
}
}
The persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="2.1">
<persistence-unit name="scuoleSciPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.storassa.javaee.scuolesci.Athlete</class>
<properties>
<property name="eclipselink.target-database" value="DERBY" />
<property name="eclipselink.jdbc.driver"
value="org.apache.derby.jdbc.ClientDriver" />
<property name="eclipselink.jdbc.url"
value="jdbc:derby://localhost:1527;create=true" />
<property name="eclipselink.jdbc.user" value="APP" />
<property name="eclipselink.jdbc.password" value="APP" />
<property name="eclipselink.ddl-generation" value=" drop-and-create-tables" />
<property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.deploy-on-startup" value="true" />
</properties>
</persistence-unit>
</persistence>
The error returned on the browser
type Exception report
message Internal Server Error
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: javax.ejb.EJBException: Transaction aborted
root cause
javax.faces.el.EvaluationException: javax.ejb.EJBException: Transaction aborted
root cause
javax.ejb.EJBException: Transaction aborted
root cause
javax.transaction.RollbackException: Transaction marked for rollback.
root cause
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Table/View 'ATHLETE' does not exist.
Error Code: -20001
Call: INSERT INTO ATHLETE (ID, BIRTH, NAME, SURNAME) VALUES (?, ?, ?, ?)
bind => [4 parameters bound]
Query: InsertObjectQuery(com.storassa.javaee.scuolesci.Athlete#65fd5648)
root cause
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Table/View 'ATHLETE' does not exist.
Error Code: -20001
Call: INSERT INTO ATHLETE (ID, BIRTH, NAME, SURNAME) VALUES (?, ?, ?, ?)
bind => [4 parameters bound]
Query: InsertObjectQuery(com.storassa.javaee.scuolesci.Athlete#65fd5648)
root cause
java.sql.SQLSyntaxErrorException: Table/View 'ATHLETE' does not exist.
root cause
org.apache.derby.client.am.SqlException: Table/View 'ATHLETE' does not exist.
I don't provide web-related resource/classes as I don't think they can be useful. In case let me know.
Should the table ATHLETE be created due to the #Entity annotation and the ?

I guess the problem is related to leading space in eclipselink.ddl-generation value. In other words try to replace:
<property name="eclipselink.ddl-generation" value=" drop-and-create-tables" />
with
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />

Related

NamedQuery not found Hibernate4 Seam 2.2 JPA 2.0 and Jboss eap 6

I am receiving the Named Query not found error message on JBOSS EAP 6.3 server. I am using Hibernate4 Seam 2.2 JPA 2.0 and Jboss eap 6 in my application.
Caused by: java.lang.IllegalArgumentException: Named query not found: findOfficerByEmpIDFetchAssigners
at org.hibernate.ejb.AbstractEntityManagerImpl.createNamedQuery(AbstractEntityManagerImpl.java:601) [hibernate-entitymanager-4.2.14.SP1-redhat-1.jar:4.2.14.SP1-redhat-1]
at org.jboss.seam.persistence.EntityManagerProxy.createNamedQuery(EntityManagerProxy.java:46) [jboss-seam-2.2.0.GA.jar:2.2.0.GA]
at com.wachovia.apps.amaster.BatchProcessorBean.getLoggedInUser(BatchProcessorBean.java:68) [amaster-ejb-1.0.jar:]
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="AccountMaster">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/jdbc/AccountMaster</jta-data-source>
<properties>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider"/>
<property name="hibernate.cache.use_query_cache" value="false"/>
<property name="hibernate.show_sql" value="false"/>
<property name="jboss.entity.manager.jndi.name" value="java:jboss/AmasterEntityManager"/>
<property name="jboss.entity.manager.factory.jndi.name" value="java:jboss/AmasterEntityManagerFactory"/>
<property name="hibernate.default_schema" value="AMASTER"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.id.new_generator_mappings" value="false"/>
<property name="jboss.as.jpa.managed" value="false"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
<property name="jboss.as.jpa.adapterModule" value="org.jboss.as.jpa.hibernate:4"/>
<property name="jboss.as.jpa.adapterClass" value="org.jboss.as.jpa.hibernate4.HibernatePersistenceProviderAdaptor"/>
</properties>
My Entity class,
#Entity
#Table(name="OFFICER")
#NamedQueries({
#NamedQuery(name="findOfficerByEmployeeId",
query="from Officer where upper(employeeId)=upper(:id) order by employeeId"),
#NamedQuery(name="findOfficerByEmpIDFetchAssigners",
query="from Officer o left join fetch o.assigners ass where upper(o.employeeId) = :id")
})
public class Officer implements java.io.Serializable {
And Here is my Stateless bean class I am calling the NamedQuery,
#Stateless
#Name("batchProcessor")
#AutoCreate
#TransactionManagement(TransactionManagementType.BEAN)
public class BatchProcessorBean implements BatchProcessor, Serializable {
private static final long serialVersionUID = 395715959808111918L;
#SuppressWarnings("seam-unresolved-variable")
#In(value = "entityManager")
private EntityManager em;
public Officer getLoggedInUser(String employeeID) {
UserTransaction instance = Transaction.instance();
List<Officer> list = em.createNamedQuery("findOfficerByEmpIDFetchAssigners").setParameter("id", employeeID).getResultList();
I placed the persistence.xml in the under ejb/resources/META-INF folder. I have tried the previous posts regarding the NamedQuery Not found issue. That is not fixing my issue
Please help me to figure out the issue. Thanks
I have resolved the issue. I have added the the following class tag in persistence.xml to resolve the issue,
<class>com.wachovia.apps.amaster.orm.Officer</class>
The order of the tags are important in persistence.xml. In my case, this class tag must be added before the <properties> tag and after the <jta-data-source> tag.

Persistence unit for class issue

I am using Kundera with mongodb on a windows 7 box. I am trying to use int data type. But I am getting the following error.
Exception in thread "main" com.impetus.kundera.configure.schema.SchemaGenerationException: Persistence unit for class : int is not loaded
at com.impetus.kundera.configure.SchemaConfiguration.parseRelations(SchemaConfiguration.java:262)
at com.impetus.kundera.configure.SchemaConfiguration.configure(SchemaConfiguration.java:151)
at com.impetus.kundera.configure.ClientMetadataBuilder.buildClientFactoryMetadata(ClientMetadataBuilder.java:48)
at com.impetus.kundera.persistence.EntityManagerFactoryImpl.configureClientFactories(EntityManagerFactoryImpl.java:404)
at com.impetus.kundera.persistence.EntityManagerFactoryImpl.configure(EntityManagerFactoryImpl.java:157)
at com.impetus.kundera.persistence.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:131)
at com.impetus.kundera.KunderaPersistence.createEntityManagerFactory(KunderaPersistence.java:85)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at com.atomconnect.App.insertIntoMongo(App.java:37)
at com.atomconnect.App.main(App.java:53)
My entity object has the following fields
#Id
#Column(name="MESSAGE_ID")
private String messageId;
#Column(name = "SUBJECT")
private String subject;
#Column(name = "BODY")
private String body;
#Column(name = "zipcode")
private int zipcode;
#Embedded
private Contact from;
My persistence.xml looks like below
<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="2.0">
<persistence-unit name="ac">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<properties>
<property name="kundera.nodes" value="localhost" />
<property name="kundera.port" value="12345" />
<property name="kundera.keyspace" value="test" />
<property name="kundera.dialect" value="mongodb" />
<property name="kundera.client.lookup.class" value="com.impetus.client.mongodb.MongoDBClientFactory" />
<property name="" value="datastore_mongo.jar"/>
<!-- <property name="kundera.cache.provider.class" value="com.impetus.kundera.cache.ehcache.EhCacheProvider" />
<property name="kundera.cache.config.resource" value="/ehcache-test.xml" /> -->
</properties>
<jar-file>target/test.jar</jar-file>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
</persistence>
I wasted 2 days around this but not able to get the solution. Any help would be appreciated
Can you try removing
property name="" value="datastore_mongo.jar"
and share test.jar entities code ? Also , which version of Kundera are you using ?
I had a class for which I have declared the one to one mapping annotation for a int data type which was never used.
This should not cause any problem but the way kundera populates metadata via reflection is the issue.

Spring MVC - nested exception is java.lang.RuntimeException: org.postgresql.util.PSQLException: ERROR: relation "userid" does not exist

I am making a simple spring MVC application that takes data from a view and sends it to a PostgreSQL database on my machine. I have been following tutorials and am not completely familiar with the bean configuration style of handling connection settings in the Data Access Objects. The error that returns when I attempt to post to the database is as follows:
HTTP Status 500 - Request processing failed; nested exception is java.lang.RuntimeException: org.postgresql.util.PSQLException: ERROR: relation "userid" does not exist
"userid" is my simple postgre table I'm using for testing.
My spring bean configuration file is this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/postgres" />
<property name="username" value="postgres" />
<property name="password" value="kittens" />
</bean>
This is the DAO handling the connection to the DB:
package com.ARSmvcTest.dao.impl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.ARSmvcTest.dao.arsDAO;
import com.ARSmvcTest.models.ARS;
public class JDBCarsDAO implements arsDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void insert(ARS ars){
String sql = "INSERT INTO UserID " +
"(ID_, First_, Last_, Email_, Pwd_) VALUES (?, ?, ?, ?, ?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, ars.getID_());
ps.setString(2, ars.getFirst_());
ps.setString(3, ars.getLast_());
ps.setString(5, ars.getPwd_());
ps.setString(4, ars.getEmail_());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
// FIND ARS BY ID WILL GO HERE EVENTUALLY
}
The spring bean is passing data to the connection successfully as evidenced by this screenshot below:
http://i.imgur.com/Hb7O5Qi.png (apologies, new user and can't embed images)
Despite the dataSource object receiving connection properties from my above spring bean, I notice that the ConnectionProperties field is still null.
Is this what is causing my exception on the Insert attempt?
Lastly I will include a screenshot of the Exception and stack being displayed in browser at the moment of failure:
http://i.imgur.com/prj1HtY.png (apologies, can't embed images)
this exception is directly triggered from the database(-driver).
It tells you that the table named "userid" is not existing.
Please check:
the table name on database and your insert-statement
if the table is read and writabled for the user you use for your connection; you need to have grated the correct right to be able to see and write to the table
I hope this will help you as this seems to be the typical error for this kind of exception.

WEB9031 - cannot store entity with sequence generated id

I am using glassfish, postgres and openjpa.
I only have one bean and first want to create a new intance and store it in DB. I created a new User-Object, filled it (except the id) and got - trying to persist - following exception:
Caused by: java.lang.IllegalStateException: WEB9031: WebappClassLoader unable to load resource [org.apache.openjpa.util.LongId], because it has not yet been started, or was already stopped
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1401)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
at org.myPlace.server.user.UserPDO.pcNewObjectIdInstance(UserPDO.java)
at org.apache.openjpa.enhance.PCRegistry.newObjectId(PCRegistry.java:142)
at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClass(MetaDataRepository.java:1694)
at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClasses(MetaDataRepository.java:1644)
... 128 more
WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for
servlet Faces Servlet threw exception
java.lang.IllegalStateException: WEB9031: WebappClassLoader unable to load resource
[org.apache.openjpa.util.LongId], because it has not yet been started, or was already stopped
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1401)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
at org.myPlace.server.user.UserPDO.pcNewObjectIdInstance(UserPDO.java)
at org.apache.openjpa.enhance.PCRegistry.newObjectId(PCRegistry.java:142)
at org.apache.openjpa.meta.MetaDataRepository.processRegisteredClass(MetaDataRepository.java:1694)
My bean looks like this:
#Entity
#Table(name="tbl_User")
public class UserPDO implements Serializable {
private long id;
private String username;
private String password;
public UserPDO() {}
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="user_seq_gen")
#SequenceGenerator(name="user_seq_gen", sequenceName="user_seq")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
... }
My persistence.xml looks like this:
<?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="myPlace" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>org.myPlace.server.user.UserPDO</class>
<properties>
<property name="openjpa.jdbc.DBDictionary" value="postgres"/>
<property name="openjpa.ConnectionDriverName" value="org.postgresql.Driver"/>
<property name="openjpa.ConnectionURL" value="jdbc:postgresql://localhost:5432/myPlace"/>
<property name="openjpa.ConnectionPassword" value="myPlace"/>
<property name="openjpa.ConnectionUserName" value="myPlace"/>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema"/>
<property name="openjpa.Log" value="File=/home/username/apache.log, DefaultLevel=ERROR, Tool=INFO, SQL=TRACE"/>
<property name="openjpa.DynamicEnhancementAgent" value="false" />
<property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" />
<property name="openjpa.DataCache" value="false"/>
<property name="openjpa.QueryCache" value="false"/>
</properties>
</persistence-unit>
The table is created correctly, so is the sequence. But when I want to create a new user object via
public <T> T create(T t) {
this.em.persist(t);
this.em.flush();
this.em.refresh(t);
return t;
}
I get the exception mentioned above. I found some questions/answers here that suggest that deactiving runtime-enhancement should do the trick. But it didn't work for me. My first idea was, that it might be a Classloader-Leak. I copied postgres-driver and openjpa-jars into the glassfish/lib-folder.
Can anybody help? Thanks!

JTA not rolling back when deleting cascade fails

Using: Glassfish 3.1.2, EclipseLink.
I have the following three-classes JPA model:
#Entity public class Customer implements Serializable {
#Id private Integer id;
#OneToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}, orphanRemoval=true)
private Person person;
[...]
#Entity public class Person implements Serializable {
#Id private Integer id;
[...]
#Entity public class Request implements Serializable {
#Id private Integer id;
#ManyToOne private Person person;
I try to remove a customer with the following strategy (using CMT):
<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="MyPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="database"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="eclipselink.logging.logger" value="DefaultLogger"/>
<property name="eclipselink.logging.timestamp" value="true"/>
<property name="eclipselink.logging.session" value="false"/>
<property name="eclipselink.logging.thread" value="false"/>
</properties>
</persistence-unit>
[...]
#PersistenceContext(unitName="MyPU")
private EntityManager entityManager;
#Resource private SessionContext context;
[...]
public void delete(Entity object) {
try{
object = this.getEntityManager().merge(object);
this.getEntityManager().remove(object);
} catch (Exception e){
this.context.setRollbackOnly();
}
}
When the Customer object is attached to a Person object that is attached to a Request, the delete cascade of Person fails causing the transaction to rollback, but the Customer is deleted from the database. I receive the following error:
INFO: [EL Fine]: 2012-12-28 10:53:38.1--Connection(27132168)--DELETE FROM CUSTOMER WHERE (ID = ?)
bind => [97]
INFO: [EL Fine]: 2012-12-28 10:53:38.125--Connection(27132168)--DELETE FROM PERSON WHERE (ID = ?)
bind => [111]
INFO: [EL Fine]: 2012-12-28 10:53:38.126--SELECT 1
WARNING: DTX5014: Caught exception in beforeCompletion() callback:
Local Exception Stack:
INFO: [EL Warning]: 2012-12-28 10:53:38.127--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERRO: atualização ou exclusão em tabela "person" viola restrição de chave estrangeira "fk_request_person_id" em "request"
Detalhe: Chave (id)=(111) ainda é referenciada pela tabela "request".
Error Code: 0
Call: DELETE FROM PERSON WHERE (ID = ?)
bind => [111]
Query: DeleteObjectQuery(111)
[...]
SEVERE: javax.ejb.EJBException: Transaction aborted
[...]
So, how can i cancel the customer removal when the cascade deletion fails?
There are two things that possible may go wrong here.
The transaction boundaries are not correctly specified
Maybe due to this, your application server does not issue the BEGIN statement correctly. This would explain that Postgres has a problem, while Oracle does not (it implicitly starts a transaction). Make sure your service methods wear the correct annotations. If everything is fine, maybe
There is a problem with your datasource.
Is it a JTA compatible datasource? Does it use the correct driver for Postgres? Please post your config so that we can check out.
I found an interesting link that may help you as well. It is about Postgres staying in autocommit mode (although when using Spring):
http://archives.postgresql.org/pgsql-jdbc/2007-07/msg00115.php