JPA can't access PostgreSQL due to cast problems - java

I'm writing a Java ee7 Webapp with PostgreSQL 9.1.1, Glassfish 4, EclipseLink 2.
My problem is, that I can't access some tables of the database.
I have two (actually 3) entity-classes, which I autogenerated with netbeans from my DB.
#Entity
#Table(name = "webappuser")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Webappuser.findAll", query = "SELECT w FROM Webappuser w"),
#NamedQuery(name = "Webappuser.findById", query = "SELECT w FROM Webappuser w WHERE w.id = :id"),
#NamedQuery(name = "Webappuser.findByUsername", query = "SELECT w FROM Webappuser w WHERE w.username = :username"),
#NamedQuery(name = "Webappuser.findByIsadmin", query = "SELECT w FROM Webappuser w WHERE w.isadmin = :isadmin"),
#NamedQuery(name = "Webappuser.findByPassword", query = "SELECT w FROM Webappuser w WHERE w.password = :password"),
#NamedQuery(name = "Webappuser.findBySalt", query = "SELECT w FROM Webappuser w WHERE w.salt = :salt")})
public class Webappuser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 30)
#Column(name = "username")
private String username;
#Column(name = "isadmin")
private Boolean isadmin;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 64)
#Column(name = "password")
private String password;
#Size(max = 32)
#Column(name = "salt")
private String salt;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private Collection<Cardbox> cardboxCollection;
public Webappuser() {
}
public Webappuser(Integer id) {
this.id = id;
}
public Webappuser(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Boolean getIsadmin() {
return isadmin;
}
public void setIsadmin(Boolean isadmin) {
this.isadmin = isadmin;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
#XmlTransient
public Collection<Cardbox> getCardboxCollection() {
return cardboxCollection;
}
public void setCardboxCollection(Collection<Cardbox> cardboxCollection) {
this.cardboxCollection = cardboxCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Webappuser)) {
return false;
}
Webappuser other = (Webappuser) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Webappuser[ id=" + id + " ]";
}
}
d
#Entity
#Table(name = "cardbox")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Cardbox.findAll", query = "SELECT c FROM Cardbox c"),
#NamedQuery(name = "Cardbox.findById", query = "SELECT c FROM Cardbox c WHERE c.id = :id"),
#NamedQuery(name = "Cardbox.findByCreated", query = "SELECT c FROM Cardbox c WHERE c.created = :created"),
#NamedQuery(name = "Cardbox.findByName", query = "SELECT c FROM Cardbox c WHERE c.name = :name"),
#NamedQuery(name = "Cardbox.findByUser", query = "SELECT c FROM Cardbox c WHERE c.user = :user")})
public class Cardbox implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "created")
#Temporal(TemporalType.DATE)
private Date created;
#Size(max = 30)
#Column(name = "name")
private String name;
#JoinColumn(name = "user", referencedColumnName = "id")
#ManyToOne(optional = false)
private Webappuser user;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "cardbox")
private Collection<Card> cardCollection;
public Cardbox() {
}
public Cardbox(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Webappuser getUser() {
return user;
}
public void setUser(Webappuser user) {
this.user = user;
}
#XmlTransient
public Collection<Card> getCardCollection() {
return cardCollection;
}
public void setCardCollection(Collection<Card> cardCollection) {
this.cardCollection = cardCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Cardbox)) {
return false;
}
Cardbox other = (Cardbox) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Cardbox[ id=" + id + " ]";
}
}
I try to access my data with EJBs
import entity.Cardbox;
import entity.Webappuser;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Named
#Stateless
public class Dao {
#PersistenceContext
EntityManager em;
public Collection<Cardbox> getAllCardboxes() {
return em.createNamedQuery("Cardbox.findAll").getResultList();
}
public Collection<Cardbox> getAllCardboxByUser() {
Webappuser user = em.createNamedQuery("Webappuser.findByUsername", Webappuser.class)
.setParameter("username", "haha")
.getSingleResult();
return em.createNamedQuery("Cardbox.findByUser", Cardbox.class)
.setParameter("user", user).getResultList();
}
//This works
public Webappuser getAllUser() {
return em.createNamedQuery("Webappuser.findByUsername", Webappuser.class)
.setParameter("username", "haha")
.getSingleResult();
}
}
Access via JSF
<h:form>
<h:dataTable value="#{dao.allCardboxes}" var="cardbox">
<h:column>#{cardbox.name}</h:column>
</h:dataTable>
<h:dataTable value="#{dao.allCardboxByUser}" var="cardboxOfUser">
<h:column>#{cardboxOfUser.id}</h:column>
</h:dataTable>
<h:dataTable value="#{dao.allUser}" var="user">
<h:column>#{user.username}</h:column>
</h:dataTable>
</h:form>
Errors I get with ´dao.allCardboxes´ (Had to leave to top part out, due to too many characters)
javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4475)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2009)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1979)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at sun.proxy.$Proxy526.getAllCardboxes(Unknown Source)
at ejb.__EJB31_Generated__Dao__Intf____Bean__.getAllCardboxes(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-3001] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ConversionException
Exception Description: The object [postgres], of class [class java.lang.String], could not be converted to [class java.lang.Integer].
Internal Exception: java.lang.NumberFormatException: For input string: "postgres"
at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:479)
at ejb.Dao.getAllCardboxes(Dao.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
at sun.reflect.GeneratedMethodAccessor114.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.GeneratedMethodAccessor153.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
... 74 more
Caused by: Exception [EclipseLink-3001] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ConversionException
Exception Description: The object [postgres], of class [class java.lang.String], could not be converted to [class java.lang.Integer].
Internal Exception: java.lang.NumberFormatException: For input string: "postgres"
at org.eclipse.persistence.exceptions.ConversionException.couldNotBeConverted(ConversionException.java:87)
at org.eclipse.persistence.internal.helper.ConversionManager.convertObjectToInteger(ConversionManager.java:542)
at org.eclipse.persistence.internal.helper.ConversionManager.convertObject(ConversionManager.java:116)
at org.eclipse.persistence.internal.databaseaccess.DatasourcePlatform.convertObject(DatasourcePlatform.java:179)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.extractPrimaryKeyFromRow(ObjectBuilder.java:2805)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.extractPrimaryKeyFromExpression(ObjectBuilder.java:2651)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.checkCacheForObject(ExpressionQueryMechanism.java:869)
at org.eclipse.persistence.queries.ReadObjectQuery.checkEarlyReturnLocal(ReadObjectQuery.java:245)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.checkEarlyReturn(ObjectLevelReadQuery.java:833)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:836)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1114)
at org.eclipse.persistence.queries.ReadObjectQuery.execute(ReadObjectQuery.java:429)
at org.eclipse.persistence.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:3207)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1797)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1779)
at org.eclipse.persistence.internal.indirection.NoIndirectionPolicy.valueFromQuery(NoIndirectionPolicy.java:326)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRowInternal(ForeignReferenceMapping.java:2234)
at org.eclipse.persistence.mappings.OneToOneMapping.valueFromRowInternal(OneToOneMapping.java:1790)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java:2120)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.readFromRowIntoObject(ForeignReferenceMapping.java:1455)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:455)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:862)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneNormally(ObjectBuilder.java:777)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:730)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:629)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:587)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:571)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:782)
at org.eclipse.persistence.queries.ReadAllQuery.registerResultInUnitOfWork(ReadAllQuery.java:848)
at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:490)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1155)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1114)
at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:402)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1202)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2894)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1797)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1779)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1744)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:258)
at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:468)
... 103 more
Caused by: java.lang.NumberFormatException: For input string: "postgres"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.valueOf(Integer.java:582)
at org.eclipse.persistence.internal.helper.ConversionManager.convertObjectToInteger(ConversionManager.java:527)
... 142 more
Errors I get with ´dao.allCardboxByUser´
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: FEHLER: Operator existiert nicht: name = integer
Hinweis: Kein Operator stimmt mit dem angegebenen Namen und den Argumenttypen überein. Sie müssen möglicherweise ausdrückliche Typumwandlungen hinzufügen.
Position: 57
Error Code: 0
Call: SELECT id, created, name, user FROM cardbox WHERE (user = ?)
bind => [1 parameter bound]
Query: ReadAllQuery(name="Cardbox.findByUser" referenceClass=Cardbox sql="SELECT id, created, name, user FROM cardbox WHERE (user = ?)")
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:377)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
at sun.reflect.GeneratedMethodAccessor114.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.GeneratedMethodAccessor153.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
... 74 more
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: FEHLER: Operator existiert nicht: name = integer
Hinweis: Kein Operator stimmt mit dem angegebenen Namen und den Argumenttypen überein. Sie müssen möglicherweise ausdrückliche Typumwandlungen hinzufügen.
Position: 57
Error Code: 0
Call: SELECT id, created, name, user FROM cardbox WHERE (user = ?)
bind => [1 parameter bound]
Query: ReadAllQuery(name="Cardbox.findByUser" referenceClass=Cardbox sql="SELECT id, created, name, user FROM cardbox WHERE (user = ?)")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:679)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1995)
at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:570)
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.executeSelectCall(DatasourceCallQueryMechanism.java:299)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.selectAllRows(DatasourceCallQueryMechanism.java:694)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRowsFromTable(ExpressionQueryMechanism.java:2714)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRows(ExpressionQueryMechanism.java:2667)
at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:477)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1155)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:899)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1114)
at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:402)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1202)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2894)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1797)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1779)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1744)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:258)
... 104 more
Caused by: org.postgresql.util.PSQLException: FEHLER: Operator existiert nicht: name = integer
Hinweis: Kein Operator stimmt mit dem angegebenen Namen und den Argumenttypen überein. Sie müssen möglicherweise ausdrückliche Typumwandlungen hinzufügen.
Position: 57
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2157)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1886)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:555)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:417)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:302)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeSelect(DatabaseAccessor.java:1002)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:641)
... 124 more
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="CardMKNPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>flashMKN</jta-data-source>
<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"/>
</properties>
</persistence-unit>
</persistence>

Your name query("Cardbox.findByUser") should be like below. Currently you are using another object in where condition instead of a field.
SELECT c FROM cardbox c WHERE c.user.username = :user
Here c.user represents the Entity Webappuser which has the field username.

Related

Problem in creating new instance using the default constructor. The default constructor triggered an exception

I'm having issues when trying to deploy my enterprise java bean application to GlassFish server 5.1.0. My errors are shown here:
Exception while deploying the app [ED-EMS-SLSB]|#]
Exception during lifecycle processing
org.glassfish.deployment.common.DeploymentException: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [ED-EMS-SLSB-ejbPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
---------------------------------------------------------
Exception [EclipseLink-168] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Problem in creating new instance using the default constructor. The default constructor triggered an exception.
Internal Exception: java.lang.reflect.InvocationTargetException
Target Invocation Exception: java.lang.RuntimeException:
Descriptor: RelationalDescriptor(entity.EmsEmployee --> [DatabaseTable(EMS_EMPLOYEE)])
Runtime Exceptions:
---------------------------------------------------------
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createDeployFailedPersistenceException(EntityManagerSetupImpl.java:908)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:848)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:219)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:327)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:350)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:313)
at org.glassfish.persistence.jpa.JPADeployer$2.visitPUD(JPADeployer.java:427)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:486)
at org.glassfish.persistence.jpa.JPADeployer.iterateInitializedPUsAtApplicationPrepare(JPADeployer.java:468)
at org.glassfish.persistence.jpa.JPADeployer.event(JPADeployer.java:371)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:107)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:463)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:195)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:467)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:516)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:512)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:511)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:542)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:534)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:533)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1441)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:86)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1823)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1699)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:510)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:200)
at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:166)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:439)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:144)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:515)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
at java.lang.Thread.run(Thread.java:748)
|#]
Exception while deploying the app [ED-EMS-SLSB] : Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [ED-EMS-SLSB-ejbPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
---------------------------------------------------------
Exception [EclipseLink-168] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Problem in creating new instance using the default constructor. The default constructor triggered an exception.
Internal Exception: java.lang.reflect.InvocationTargetException
Target Invocation Exception: java.lang.RuntimeException:
Descriptor: RelationalDescriptor(entity.EmsEmployee --> [DatabaseTable(EMS_EMPLOYEE)])
Runtime Exceptions:
---------------------------------------------------------
|#]
I'm hoping someone could shed some light on this as this is my first time dealing with Enterprise Java Beans and I find it to be very difficult, considering that everything has to be setup a certain way. If anyone can recommend something or point me in the right direction, that'll be great.
Edit:
This is my entity class EmsEmployee.java
/*
* 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 entity;
import java.io.Serializable;
import java.math.BigDecimal;
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 jeremy
*/
#Entity
#Table(name = "EMS_EMPLOYEE")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "EmsEmployee.findAll", query = "SELECT e FROM EmsEmployee e"),
#NamedQuery(name = "EmsEmployee.findByEmpid", query = "SELECT e FROM EmsEmployee e WHERE e.empid = :empid"),
#NamedQuery(name = "EmsEmployee.findByName", query = "SELECT e FROM EmsEmployee e WHERE e.name = :name"),
#NamedQuery(name = "EmsEmployee.findByPassword", query = "SELECT e FROM EmsEmployee e WHERE e.password = :password"),
#NamedQuery(name = "EmsEmployee.findByEmail", query = "SELECT e FROM EmsEmployee e WHERE e.email = :email"),
#NamedQuery(name = "EmsEmployee.findByPhone", query = "SELECT e FROM EmsEmployee e WHERE e.phone = :phone"),
#NamedQuery(name = "EmsEmployee.findByAddress", query = "SELECT e FROM EmsEmployee e WHERE e.address = :address"),
#NamedQuery(name = "EmsEmployee.findBySecqn", query = "SELECT e FROM EmsEmployee e WHERE e.secqn = :secqn"),
#NamedQuery(name = "EmsEmployee.findBySecans", query = "SELECT e FROM EmsEmployee e WHERE e.secans = :secans"),
#NamedQuery(name = "EmsEmployee.findByBsbid", query = "SELECT e FROM EmsEmployee e WHERE e.bsbid = :bsbid"),
#NamedQuery(name = "EmsEmployee.findByAccid", query = "SELECT e FROM EmsEmployee e WHERE e.accid = :accid"),
#NamedQuery(name = "EmsEmployee.findBySalary", query = "SELECT e FROM EmsEmployee e WHERE e.salary = :salary"),
#NamedQuery(name = "EmsEmployee.findByAppgroup", query = "SELECT e FROM EmsEmployee e WHERE e.appgroup = :appgroup"),
#NamedQuery(name = "EmsEmployee.findByActive", query = "SELECT e FROM EmsEmployee e WHERE e.active = :active"),
#NamedQuery(name = "EmsEmployee.findByMemo", query = "SELECT e FROM EmsEmployee e WHERE e.memo = :memo")})
public class EmsEmployee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 6)
#Column(name = "EMPID")
private String empid;
#Size(max = 50)
#Column(name = "NAME")
private String name;
#Size(max = 64)
#Column(name = "PASSWORD")
private String password;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Size(max = 50)
#Column(name = "EMAIL")
private String email;
// #Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
#Size(max = 10)
#Column(name = "PHONE")
private String phone;
#Size(max = 50)
#Column(name = "ADDRESS")
private String address;
#Size(max = 60)
#Column(name = "SECQN")
private String secqn;
#Size(max = 60)
#Column(name = "SECANS")
private String secans;
#Size(max = 6)
#Column(name = "BSBID")
private String bsbid;
#Size(max = 10)
#Column(name = "ACCID")
private String accid;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "SALARY")
private BigDecimal salary;
#Size(max = 15)
#Column(name = "APPGROUP")
private String appgroup;
#Column(name = "ACTIVE")
private Boolean active;
#Size(max = 255)
#Column(name = "MEMO")
private String memo;
public EmsEmployee() {
}
public EmsEmployee(String empid) {
this.empid = empid;
}
public String getEmpid() {
return empid;
}
public void setEmpid(String empid) {
this.empid = empid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSecqn() {
return secqn;
}
public void setSecqn(String secqn) {
this.secqn = secqn;
}
public String getSecans() {
return secans;
}
public void setSecans(String secans) {
this.secans = secans;
}
public String getBsbid() {
return bsbid;
}
public void setBsbid(String bsbid) {
this.bsbid = bsbid;
}
public String getAccid() {
return accid;
}
public void setAccid(String accid) {
this.accid = accid;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public String getAppgroup() {
return appgroup;
}
public void setAppgroup(String appgroup) {
this.appgroup = appgroup;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
#Override
public int hashCode() {
int hash = 0;
hash += (empid != null ? empid.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 EmsEmployee)) {
return false;
}
EmsEmployee other = (EmsEmployee) object;
if ((this.empid == null && other.empid != null) || (this.empid != null && !this.empid.equals(other.empid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.EmsEmployee[ empid=" + empid + " ]";
}
}
This is my stateless session bean class EmsEmployeeFacade.java
/*
* 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 session;
import entity.EmsEmployee;
import entity.EmsEmployeeDTO;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author jeremy
*/
#Stateless
public class EmsEmployeeFacade implements EmsEmployeeFacadeRemote {
#PersistenceContext(unitName = "ED-EMS-SLSB-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
private void create(EmsEmployee emsEmployee) {
em.persist(emsEmployee);
}
private void edit(EmsEmployee emsEmployee) {
em.merge(emsEmployee);
}
private void remove(EmsEmployee emsEmployee) {
em.remove(em.merge(emsEmployee));
}
private EmsEmployee find(Object id) {
return em.find(EmsEmployee.class, id);
}
private EmsEmployee myDTO2DAO(EmsEmployeeDTO emsEmployeeDTO) {
EmsEmployee emsEmployee = new EmsEmployee();
emsEmployee.setEmpid(emsEmployeeDTO.getEmpid());
emsEmployee.setName(emsEmployeeDTO.getName());
emsEmployee.setPassword(emsEmployeeDTO.getPassword());
emsEmployee.setEmail(emsEmployeeDTO.getEmail());
emsEmployee.setPhone(emsEmployeeDTO.getPhone());
emsEmployee.setAddress(emsEmployeeDTO.getAddress());
emsEmployee.setSecqn(emsEmployeeDTO.getSecqn());
emsEmployee.setSecans(emsEmployeeDTO.getSecans());
emsEmployee.setBsbid(emsEmployeeDTO.getBsbid());
emsEmployee.setAccid(emsEmployeeDTO.getAccid());
emsEmployee.setSalary(emsEmployeeDTO.getSalary());
emsEmployee.setAppgroup(emsEmployeeDTO.getAppgroup());
emsEmployee.setActive(emsEmployeeDTO.getActive());
emsEmployee.setMemo(emsEmployeeDTO.getMemo());
return emsEmployee;
}
#Override
public boolean createRecord(EmsEmployeeDTO emsEmployeeDTO) {
// try to find the database record in the database first
EmsEmployee tmpEmployee = em.find(EmsEmployee.class, emsEmployeeDTO.getEmpid());
if (tmpEmployee != null) {
// employee whose empid can be found; should not add the record
return false;
}
// employee whose empid could not be found; add it to the database
try {
// convert a DTO to DAO
EmsEmployee emsEmployee = this.myDTO2DAO(emsEmployeeDTO);
// add to database via JPA
this.create(emsEmployee);
return true;
} catch (Exception ex) {
// something is wrong, should not be here though
return false;
}
}
}
You are using GlassFish 5.1.0 and this only supports Java 8.
I assume that you are using a newer Java version (probably 14) that causes this exception.

Field 'fieldName' doesn't have a default value in ManyToMany relation

I am having the following entities which are in ManyToMany relation.
UpdateKeyEntity.java
#Embeddable
public class UpdateKeyEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "product_name")
private String productName;
#Column(name = "product_base_version")
private String productBaseVersion;
#Column(name = "update_level")
private int updateLevel;
#Column(name = "channel")
private String channel;
public UpdateKeyEntity() {
}
public UpdateKeyEntity(String productName, String productBaseVersion, int updateLevel, String channel) {
this.productName = productName;
this.productBaseVersion = productBaseVersion;
this.updateLevel = updateLevel;
this.channel = channel;
}
#Override
public int hashCode() {
return Objects.hash(this.productName, this.productBaseVersion, this.channel, this.updateLevel);
}
#Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof UpdateKeyEntity) {
UpdateKeyEntity updateKeyEntity = (UpdateKeyEntity) obj;
return this.productName.equals(updateKeyEntity.getProductName()) && this.productBaseVersion.equals(
updateKeyEntity.getProductBaseVersion()) && this.channel.equals(updateKeyEntity.getChannel()) &&
this.updateLevel == updateKeyEntity.updateLevel;
}
return false;
}
}
UpdateEntity.java
#Entity
#Table(name = Constants.TABLE_NAME)
public class UpdateEntity {
#EmbeddedId
private UpdateKeyEntity updateKeyEntity;
#Column(name = "files_added", columnDefinition = "TEXT")
private String filesAdded;
#Column(name = "files_modified", columnDefinition = "TEXT")
private String filesModified;
#Column(name = "files_removed", columnDefinition = "TEXT")
private String filesRemoved;
#Column(name = "lifecycle_state")
private String lifeCycleState;
#ManyToMany(
cascade = {CascadeType.MERGE, CascadeType.PERSIST}
)
#JoinTable(
name = "update_level_security_advisories",
joinColumns = {
#JoinColumn(name = "product_name", referencedColumnName = "product_name"),
#JoinColumn(name = "product_base_version", referencedColumnName = "product_base_version"),
#JoinColumn(name = "update_level", referencedColumnName = "update_level"),
#JoinColumn(name = "channel", referencedColumnName = "channel")
},
inverseJoinColumns = #JoinColumn(name = "sec_ad_id", referencedColumnName = "id")
)
private Set<SecurityAdvisoryEntity> securityAdvisoryEntityList = new HashSet<>();
public UpdateEntity() {
}
public UpdateEntity(UpdateLevelDescription updateLevelDescription) {
this.updateKeyEntity = new UpdateKeyEntity(updateLevelDescription.getProductName(),
updateLevelDescription.getProductBaseVersion(), updateLevelDescription.getUpdateLevel(),
updateLevelDescription.getChannel());
this.filesAdded = updateLevelDescription.getFilesAdded();
this.filesModified = updateLevelDescription.getFilesModified();
this.filesRemoved = updateLevelDescription.getFilesRemoved();
this.lifeCycleState = updateLevelDescription.getLifeCycleState();
addSecAdd(updateLevelDescription.getSecurityAdvisoryEntitylist);
}
// getter and setters
private void addSecAdd(List<SecurityAdvisoryEntity> securityAdvisoryEntitylist) {
for (SecurityAdvisoryEntity securityAdvisoryEntity : securityAdvisoryEntitylist) {
securityAdvisoryEntityList.add(securityAdvisoryEntity);
securityAdvisoryEntity.getUpdateEntityList().add(this);
}
}
#Override
public int hashCode() {
return Objects.hash(this.updateKeyEntity.getProductBaseVersion(),
this.updateKeyEntity.getChannel(), this.updateKeyEntity.getUpdateLevel(), this.filesAdded,
this.filesModified, this.filesRemoved);
}
#Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof UpdateEntity) {
UpdateEntity updateEntity = (UpdateEntity) obj;
return (updateEntity.getUpdateKeyEntity().getProductBaseVersion().equals(this.
getUpdateKeyEntity().getProductBaseVersion()) && updateEntity.getUpdateKeyEntity().getChannel().
equals(this.getUpdateKeyEntity().getChannel()) && updateEntity.getUpdateKeyEntity().getUpdateLevel()
== this.getUpdateKeyEntity().getUpdateLevel());
}
return false;
}
}
SecurityAdvisoryEntity.java
#Entity
#Table(name = "security_advisories")
public class SecurityAdvisoryEntity {
#Id
#Column(name = "id")
private String id;
#ManyToMany(mappedBy = "securityAdvisoryEntityList")
private List<UpdateEntity> updateEntityList = new ArrayList<>();
#Column(name = "overview", columnDefinition = "TEXT")
private String overview;
#Column(name = "severity", columnDefinition = "TEXT")
private String severity;
#Column(name = "description", columnDefinition = "TEXT")
private String description;
#Column(name = "impact", columnDefinition = "TEXT")
private String impact;
#Column(name = "solution", columnDefinition = "TEXT")
private String solution;
#Column(name = "notes", columnDefinition = "TEXT")
private String notes;
#Column(name = "credits", columnDefinition = "TEXT")
private String credits;
public SecurityAdvisoryEntity(SecurityAdvisoryDescription securityAdvisoryDescription) {
this.id = securityAdvisoryDescription.getId();
this.overview = securityAdvisoryDescription.getOverview();
this.severity = securityAdvisoryDescription.getSeverity();
this.description = securityAdvisoryDescription.getDescription();
this.impact = securityAdvisoryDescription.getImpact();
this.solution = securityAdvisoryDescription.getSolution();
this.notes = securityAdvisoryDescription.getNotes();
this.credits = securityAdvisoryDescription.getCredits();
}
// getters and setters
}
When executing the following
public void persistUpdateLevelDescription(UpdateLevelDescription updateLevelDescription) throws UpdatesException {
UpdateEntity updateEntity = new UpdateEntity(updateLevelDescription);
EntityManager entityManager = getEntityManager();
try {
persistEntity(updateEntity, entityManager);
}catch (UpdatesException e) {
//log and throw
}
}
private <T> void persistEntity(T entity, EntityManager entityManager) throws UpdatesException {
int numOfAttempts = 0;
do {
numOfAttempts++;
try {
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();
return;
} catch (PersistenceException persistenceException) {
validatePersistenceException(persistenceException);
}
} while (numOfAttempts <= databaseConnection.getMaxRetries());
throw new UpdatesException("Database connection failed when inserting the provided entity");
}
I am getting the following error,
2020-04-26 21:38:24 WARN SqlExceptionHelper:129 - SQL Error: 1364, SQLState: HY000
2020-04-26 21:38:24 ERROR SqlExceptionHelper:131 - Field 'updateEntity_product_name' doesn't have a default value
2020-04-26 21:38:24 INFO AbstractBatchImpl:193 - HHH000010: On release of batch it still contained JDBC statements
2020-04-26 21:38:24 ERROR ExceptionMapperStandardImpl:39 - HHH000346: Error during managed flush [org.hibernate.exception.GenericJDBCException: could not execute statement]
2020-04-26 21:38:24 ERROR UpdatesException:29 - Database connection failed when inserting 10 update level of wso2i2-5.7.0
org.kasun.updates.updatesms.exception.UpdatesException: Database connection failed when inserting 10 update level of wso2i2-5.7.0
at org.kasun.updates.updatesms.dao.UpdatesRepository.persistUpdateLevelDescription(UpdatesRepository.java:337)
at org.kasun.updates.updatesms.UpdatesManager.persistUpdateLevelDescriptions(UpdatesManager.java:142)
at org.kasun.updates.updatesms.service.UpdatesService.updateInformation(UpdatesService.java:227)
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:498)
at org.wso2.msf4j.internal.router.HttpMethodInfo.invokeResource(HttpMethodInfo.java:187)
at org.wso2.msf4j.internal.router.HttpMethodInfo.invoke(HttpMethodInfo.java:143)
at org.wso2.msf4j.internal.MSF4JHttpConnectorListener.dispatchMethod(MSF4JHttpConnectorListener.java:218)
at org.wso2.msf4j.internal.MSF4JHttpConnectorListener.lambda$onMessage$57(MSF4JHttpConnectorListener.java:129)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.kasun.updates.updatesms.exception.UpdatesException: Exception occurred while connecting to the database
at org.kasun.updates.updatesms.dao.UpdatesRepository.validatePersistenceException(UpdatesRepository.java:740)
at org.kasun.updates.updatesms.dao.UpdatesRepository.persistEntity(UpdatesRepository.java:451)
at org.kasun.updates.updatesms.dao.UpdatesRepository.persistUpdateLevelDescription(UpdatesRepository.java:332)
... 13 more
Caused by: javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:75)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:71)
at org.kasun.updates.updatesms.dao.UpdatesRepository.persistEntity(UpdatesRepository.java:448)
... 14 more
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:56)
... 16 more
Caused by: org.hibernate.exception.GenericJDBCException: could not execute statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2934)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3434)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:582)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:456)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1397)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:473)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3133)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
... 15 more
Caused by: java.sql.SQLException: Field 'updateEntity_product_name' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2113)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2049)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2034)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
... 32 more
What I am doing wrong?

Java JPA Illegal Argument Exception - NamedQuery of name: xyz not found

I am trying to get a user based on their ID using this named query, however I keep getting an illegal argument exception. I've been looking at this code for awhile. Hopefully someone may catch something I might've missed.
This is my ORM
#Entity
#Table(name = "MYUSER")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Myuser.findAll", query = "SELECT m FROM Myuser m"),
#NamedQuery(name = "Myuser.findByUserid", query = "SELECT m FROM Myuser m WHERE m.userid = :userid"),
#NamedQuery(name = "Myuser.findByName", query = "SELECT m FROM Myuser m WHERE m.name = :name"),
#NamedQuery(name = "Myuser.findByPassword", query = "SELECT m FROM Myuser m WHERE m.password = :password"),
#NamedQuery(name = "Myuser.findByEmail", query = "SELECT m FROM Myuser m WHERE m.email = :email"),
#NamedQuery(name = "Myuser.findByTel", query = "SELECT m FROM Myuser m WHERE m.tel = :tel"),
#NamedQuery(name = "Myuser.findByAddress", query = "SELECT m FROM Myuser m WHERE m.address = :address"),
#NamedQuery(name = "Myuser.findBySecqn", query = "SELECT m FROM Myuser m WHERE m.secqn = :secqn"),
#NamedQuery(name = "Myuser.findBySecans", query = "SELECT m FROM Myuser m WHERE m.secans = :secans")})
public class Myuser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "USERID")
private Integer userid;
#Column(name = "NAME")
private String name;
#Column(name = "PASSWORD")
private String password;
#Column(name = "EMAIL")
private String email;
#Column(name = "TEL")
private Integer tel;
#Column(name = "ADDRESS")
private String address;
#Column(name = "SECQN")
private String secqn;
#Column(name = "SECANS")
private String secans;
public Myuser() {
}
public Myuser(Integer userid) {
this.userid = userid;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getTel() {
return tel;
}
public void setTel(Integer tel) {
this.tel = tel;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSecqn() {
return secqn;
}
public void setSecqn(String secqn) {
this.secqn = secqn;
}
public String getSecans() {
return secans;
}
public void setSecans(String secans) {
this.secans = secans;
}
#Override
public int hashCode() {
int hash = 0;
hash += (userid != null ? userid.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 Myuser)) {
return false;
}
Myuser other = (Myuser) object;
if ((this.userid == null && other.userid != null) || (this.userid != null && !this.userid.equals(other.userid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "ejbentity.Myuser[ userid=" + userid + " ]";
}
}
This is my user facade
#Stateless
public class MyuserFacade implements MyuserFacadeRemote {
#PersistenceContext(unitName = "EJBServer-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public MyuserFacade() {
//super(Myuser.class);
}
#Override
public Myuser getUser(int userID) {
Myuser aUser = new Myuser();
aUser = (Myuser)em.createNamedQuery("Myuser.findByUserid").setParameter("userid", userID).getResultList();
return aUser;
}
}
My persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="EJBEntityPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!--<exclude-unlisted-classes>false</exclude-unlisted-classes>-->
<class>ejbentity.Myuser</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/EA"/>
<property name="javax.persistence.jdbc.password" value="test"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.user" value="test"/>
</properties>
</persistence-unit>
</persistence>
Error Log is given below:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.appclient.client.acc.AppClientContainer.launch(AppClientContainer.java:446)
at org.glassfish.appclient.client.AppClientFacade.main(AppClientFacade.java:166)
Caused by: javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:752)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:702)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:507)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBObjectInvocationHandlerDelegate.invoke(EJBObjectInvocationHandlerDelegate.java:79)
at com.sun.proxy.$Proxy266.getUser(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.dispatchToMethod(ReflectiveTie.java:143)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:173)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.lang.IllegalArgumentException: NamedQuery of name: Myuser.findByUserid not found.
at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:355)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:1135)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createNamedQuery(EntityManagerWrapper.java:522)
at stateless.MyuserFacade.getUser(MyuserFacade.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:73)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:205)
... 19 more
Java Result: 1
Actual error:
Caused by: java.lang.IllegalArgumentException: NamedQuery of name: Myuser.findByUserid not found.
Happens from:
#NamedQuery(name = "Myuser.findByUserid", query = "SELECT m FROM Myuser m WHERE m.userid = :userid"),
UPDATE:
From your persistence.xml:
<persistence-unit name="EJBEntityPU" transaction-type="RESOURCE_LOCAL">
Here you are using transaction-type="RESOURCE_LOCAL". So if you use it, then you are responsible for EntityManager.
Then you must have to follow (JPA Concepts: JPA 101)
You must use the EntityManagerFactory to get an EntityManager
The resulting EntityManager instance is a PersistenceContext/Cache
An EntityManagerFactory can be injected via the #PersistenceUnit
annotation only (not #PersistenceContext)
You are not allowed to use #PersistenceContext to refer to a unit of
type RESOURCE_LOCAL
You must use the EntityTransaction API to begin/commit around every
call to your EntityManger
Calling entityManagerFactory.createEntityManager() twice results in
two separate EntityManager instances and therefor two separate
PersistenceContexts/Caches.
It is almost never a good idea to have more than one instance of an
EntityManager in use (don't create a second one unless you've
destroyed the first)
Solution:
This is an example. you can follow the tutorial if you want to use RESOURCE_LOCAL.
Related Link:
DON'T USE JPA'S RESOURCE_LOCAL ON THE SERVER
Persistence unit as RESOURCE_LOCAL or JTA?
persistence.xml different transaction-type attributes
We got the same error and it was because the entities were missing in persistence.xml
In your persistence.xml is:
<persistence-unit name="EJBEntityPU"
but in your MyuserFacade you use:
#PersistenceContext(unitName = "EJBServer-ejbPU")
You should change that to:
#PersistenceContext(unitName = "EJBEntityPU")
I notice you have class ejbentity.Myuser in your persistence.xml. The class actually lives in a package structure consisting of one directory called "ejbentity"? The stacktrace suggests that your Myuser class with the NamedQuery annotations is not being found, which would be explained if your package structure is not being loaded as you expect.
I don't think that transaction-type has anything to do with #NamedQuery annotation.
This error
Caused by: java.lang.IllegalArgumentException: NamedQuery of name: Myuser.findAll not found.
at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:355)
looks like an EclipseLink bug. Which version are you using ?

UnmarshalException while consuming a web service

I have a web service based on a number of entity classes. one of them is shows below
#Entity
#Table(name = "users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),
#NamedQuery(name = "Users.findByUserName", query = "SELECT u FROM Users u WHERE u.userName = :userName"),
#NamedQuery(name = "Users.findByUserPassword", query = "SELECT u FROM Users u WHERE u.userPassword = :userPassword")})
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "user_name")
private String userName;
#Basic(optional = false)
#Column(name = "user_password")
private String userPassword;
#JoinColumn(name = "user_category_id", referencedColumnName = "category_id")
#ManyToOne(optional = false)
private UserCategory userCategoryId;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userName")
private List<UserRecord> userRecordList;
public Users() {
}
public Users(String userName) {
this.userName = userName;
}
public Users(String userName, String userPassword) {
this.userName = userName;
this.userPassword = userPassword;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public UserCategory getUserCategoryId() {
return userCategoryId;
}
public void setUserCategoryId(UserCategory userCategoryId) {
this.userCategoryId = userCategoryId;
}
#XmlTransient
public List<UserRecord> getUserRecordList() {
return userRecordList;
}
public void setUserRecordList(List<UserRecord> userRecordList) {
this.userRecordList = userRecordList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (userName != null ? userName.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 Users)) {
return false;
}
Users other = (Users) object;
if ((this.userName == null && other.userName != null) || (this.userName != null && !this.userName.equals(other.userName))) {
return false;
}
return true;
}
#Override
public String toString() {
return userName;
}
}
I was able to successfully deploy the web service and then i added a new Restful web client using netbeans, which created the following class
public class Client {
private WebTarget webTarget;
private javax.ws.rs.client.Client client;
private static final String BASE_URI = "http://localhost:31691/ProductionEntitiesService/api";
public Client() {
client = javax.ws.rs.client.ClientBuilder.newClient();
webTarget = client.target(BASE_URI).path("entities.users");
}
...
public <T> T find_XML(Class<T> responseType, String id) throws ClientErrorException {
WebTarget resource = webTarget;
resource = resource.path(java.text.MessageFormat.format("{0}", new Object[]{id}));
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
public <T> T findAll_XML(Class<T> responseType) throws ClientErrorException {
WebTarget resource = webTarget;
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
public void close() {
client.close();
}
}
This line of code then returned an xml result of the query
result = c.findAll_XML(String.class);
which had this format
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<userss>
<users>
<userCategoryId>
<categoryId>2</categoryId>
<userCategory>admin</userCategory>
</userCategoryId>
<userName>admin</userName>
<userPassword>d033e22ae348aeb5660fc2140aec35850c4da997</userPassword>
</users>
</userss>
However, this line of code
List<Users> l = (List<Users>)c.findAll_XML(Users.class);
produces an exception, which seems to be caused by the "userss" tag that surrounds the xml result, I'm not sure how that came about.
Can anyone help me resolve this?
Exception in thread "AWT-EventQueue-0" javax.ws.rs.BadRequestException: HTTP 400 Bad Request
at org.glassfish.jersey.message.internal.AbstractRootElementJaxbProvider.readFrom(AbstractRootElementJaxbProvider.java:124)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:188)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:134)
at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:988)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:833)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:768)
at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:96)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:740)
at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:88)
at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:650)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:421)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:646)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:375)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:275)
at service.Client.findAll_XML(Client.java:83)
at examples.Find.<init>(Find.java:44)
at examples.Find$1.run(Find.java:166)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:744)
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.awt.EventQueue.dispatchEvent(EventQueue.java:714)
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: javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"userss"). Expected elements are <{}userCategory>,<{}users>
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:681)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:247)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:242)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:109)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1086)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:510)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:492)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:163)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:378)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:604)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3122)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:880)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:649)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:243)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:140)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:123)
at org.glassfish.jersey.message.internal.XmlRootElementJaxbProvider.readFrom(XmlRootElementJaxbProvider.java:140)
at org.glassfish.jersey.message.internal.AbstractRootElementJaxbProvider.readFrom(AbstractRootElementJaxbProvider.java:122)
... 33 more

JPA eclipse link Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

I want to persist entity object to database that contain some null values and one of the null value is a foregin key of another table that i have to fill it later and here is the sessionbean
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package boudy.sessionbeans;
import boudy.entity.Customer;
import boudy.entity.Request;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
/**
*
* #author magas
*/
#Stateless
#TransactionManagement(TransactionManagementType.BEAN)
public class RequestBean implements RequestBeanLocal {
#PersistenceContext(unitName = "InternetCompany-ejbPU")
private EntityManager em;
#Resource
private UserTransaction userTransaction;
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
public void persist(Object object) {
em.persist(object);
}
#Override
public boolean addNewCustomer() {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public boolean addNewRequest(Request requestObject) {
try {
userTransaction.begin();
em.persist(requestObject);
userTransaction.commit();
em.close();
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
}
#Override
public List<Customer> getAllCustomers() {
List<Customer> custList = null;
try {
Query query = em.createNamedQuery("Customer.findAll");
custList = query.getResultList();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return custList;
}
}
and my Entity bean is
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package boudy.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author magas
*/
#Entity
#Table(name = "request")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Request.findAll", query = "SELECT r FROM Request r"),
#NamedQuery(name = "Request.findById", query = "SELECT r FROM Request r WHERE r.id = :id"),
#NamedQuery(name = "Request.findBySalesdate", query = "SELECT r FROM Request r WHERE r.salesdate = :salesdate"),
#NamedQuery(name = "Request.findByOrganizationtype", query = "SELECT r FROM Request r WHERE r.organizationtype = :organizationtype"),
#NamedQuery(name = "Request.findByPhone", query = "SELECT r FROM Request r WHERE r.phone = :phone"),
#NamedQuery(name = "Request.findByGovernrate", query = "SELECT r FROM Request r WHERE r.governrate = :governrate"),
#NamedQuery(name = "Request.findByArea", query = "SELECT r FROM Request r WHERE r.area = :area"),
#NamedQuery(name = "Request.findByAddress", query = "SELECT r FROM Request r WHERE r.address = :address"),
#NamedQuery(name = "Request.findByPackagetype", query = "SELECT r FROM Request r WHERE r.packagetype = :packagetype"),
#NamedQuery(name = "Request.findByPeriod", query = "SELECT r FROM Request r WHERE r.period = :period"),
#NamedQuery(name = "Request.findBySpeed", query = "SELECT r FROM Request r WHERE r.speed = :speed"),
#NamedQuery(name = "Request.findByCost", query = "SELECT r FROM Request r WHERE r.cost = :cost"),
#NamedQuery(name = "Request.findByDeliveryfee", query = "SELECT r FROM Request r WHERE r.deliveryfee = :deliveryfee"),
#NamedQuery(name = "Request.findByRequestserial", query = "SELECT r FROM Request r WHERE r.requestserial = :requestserial"),
#NamedQuery(name = "Request.findByActive", query = "SELECT r FROM Request r WHERE r.active = :active"),
#NamedQuery(name = "Request.findByCondition", query = "SELECT r FROM Request r WHERE r.condition = :condition"),
#NamedQuery(name = "Request.findByReason", query = "SELECT r FROM Request r WHERE r.reason = :reason"),
#NamedQuery(name = "Request.findByCrddate", query = "SELECT r FROM Request r WHERE r.crddate = :crddate"),
#NamedQuery(name = "Request.findByDeliverydate", query = "SELECT r FROM Request r WHERE r.deliverydate = :deliverydate")})
public class Request implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "salesdate")
#Temporal(TemporalType.DATE)
private Date salesdate;
#Size(max = 45)
#Column(name = "organizationtype")
private String organizationtype;
// #Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
#Size(max = 45)
#Column(name = "phone")
private String phone;
#Size(max = 45)
#Column(name = "governrate")
private String governrate;
#Size(max = 45)
#Column(name = "area")
private String area;
#Size(max = 45)
#Column(name = "address")
private String address;
#Size(max = 45)
#Column(name = "packagetype")
private String packagetype;
#Size(max = 45)
#Column(name = "period")
private String period;
#Size(max = 45)
#Column(name = "speed")
private String speed;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "cost")
private Double cost;
#Column(name = "deliveryfee")
private Double deliveryfee;
#Size(max = 45)
#Column(name = "requestserial")
private String requestserial;
#Column(name = "active")
private Integer active;
#Size(max = 45)
#Column(name = "condition")
private String condition;
#Size(max = 100)
#Column(name = "reason")
private String reason;
#Column(name = "crddate")
#Temporal(TemporalType.DATE)
private Date crddate;
#Column(name = "deliverydate")
#Temporal(TemporalType.DATE)
private Date deliverydate;
#JoinColumn(name = "custid", referencedColumnName = "id")
#ManyToOne
private Customer custid;
#JoinColumn(name = "salesid", referencedColumnName = "emp_id")
#ManyToOne
private Employee salesid;
#JoinColumn(name = "crdid", referencedColumnName = "emp_id")
#ManyToOne
private Employee crdid;
public Request() {
}
public Request(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getSalesdate() {
return salesdate;
}
public void setSalesdate(Date salesdate) {
this.salesdate = salesdate;
}
public String getOrganizationtype() {
return organizationtype;
}
public void setOrganizationtype(String organizationtype) {
this.organizationtype = organizationtype;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getGovernrate() {
return governrate;
}
public void setGovernrate(String governrate) {
this.governrate = governrate;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPackagetype() {
return packagetype;
}
public void setPackagetype(String packagetype) {
this.packagetype = packagetype;
}
public String getPeriod() {
return period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
public Double getCost() {
return cost;
}
public void setCost(Double cost) {
this.cost = cost;
}
public Double getDeliveryfee() {
return deliveryfee;
}
public void setDeliveryfee(Double deliveryfee) {
this.deliveryfee = deliveryfee;
}
public String getRequestserial() {
return requestserial;
}
public void setRequestserial(String requestserial) {
this.requestserial = requestserial;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public Date getCrddate() {
return crddate;
}
public void setCrddate(Date crddate) {
this.crddate = crddate;
}
public Date getDeliverydate() {
return deliverydate;
}
public void setDeliverydate(Date deliverydate) {
this.deliverydate = deliverydate;
}
public Customer getCustid() {
return custid;
}
public void setCustid(Customer custid) {
this.custid = custid;
}
public Employee getSalesid() {
return salesid;
}
public void setSalesid(Employee salesid) {
this.salesid = salesid;
}
public Employee getCrdid() {
return crdid;
}
public void setCrdid(Employee crdid) {
this.crdid = crdid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Request)) {
return false;
}
Request other = (Request) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "boudy.entity.Request[ id=" + id + " ]";
}
}
and i am getting this exception
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition, cost, crddate, deliverydate, deliveryfee, governrate, organizationtyp' at line 1
Error Code: 1064
Call: INSERT INTO request (active, address, area, condition, cost, crddate, deliverydate, deliveryfee, governrate, organizationtype, packagetype, period, phone, reason, requestserial, salesdate, speed, crdid, custid, salesid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [20 parameters bound]
Query: InsertObjectQuery(boudy.entity.Request[ id=1 ])
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:840)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:906)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:592)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:535)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1717)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:253)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:207)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:193)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:342)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:162)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:177)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:472)
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:287)
at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
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:2871)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1449)
at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:224)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:123)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:3799)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1415)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:636)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1505)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3143)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:346)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:157)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:435)
at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:855)
at com.sun.enterprise.transaction.UserTransactionImpl.commit(UserTransactionImpl.java:208)
at boudy.sessionbeans.RequestBean.addNewRequest(RequestBean.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5388)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5360)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5348)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
at com.sun.proxy.$Proxy193.addNewRequest(Unknown Source)
at boudy.beans.SalesRequestBean.submitAddRequestAction(SalesRequestBean.java:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:779)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:528)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:257)
at com.sun.el.parser.AstValue.invoke(AstValue.java:248)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at boudy.filters.LoginFilter.doFilter(LoginFilter.java:114)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:744)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition, cost, crddate, deliverydate, deliveryfee, governrate, organizationtyp' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
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:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2427)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2345)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2330)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:831)
... 110 more
WARNING: Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Try replacing
#Column(name = "condition")
with
#Column(name = "`condition`")
or, if that doesn't work,
#Column(name = "\"condition\"")
MySQL is complaining because CONDITION is a reserved word and you must quote it if you wish to use it for a column name. Enclosing the column name in backticks or double quotes tells JPA to escape the column name when it passes the query to the database.
This answer goes into more detail about whether to use backticks or double quotes.
I can reconfirm that if one uses a column name which happens to be a reserved word in MySQL, then one gets the exception above ("javax.ejb.EJBException...JPA eclipse link Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException"). I spent half a day trying to figure it out because I was using 'PRIMARY' (column of type Boolean; just mentioning it but it is irrelevant to/does not affect this exception ) as a column title; which is also a Reserved Word in MySQL. The error message is rather long and only after careful consideration of what "syntax error" may mean I 'got it'.

Categories

Resources