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

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 ?

Related

happening " java.lang.ExceptionInInitializerError " Caused by " Unable to build EntityManagerFactory " in JPA project

I want create a web application and use JPA for model layer in MVC for the first time . But I'm having trouble.
The program shows me this error :
Nov 11, 2018 10:56:49 AM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Nov 11, 2018 10:56:49 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.0.Final}
Nov 11, 2018 10:56:49 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.max_fetch_depth=5, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE, hibernate.bytecode.use_reflection_optimizer=false, hibernate.jdbc.batch_versioned_data=true, hibernate.connection.pool_size=5}
Nov 11, 2018 10:56:49 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" java.lang.ExceptionInInitializerError
at model.bl.PersonManager.main(PersonManager.java:19)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: MyConnection] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:930)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:904)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:72)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at util.JPAProvider.<clinit>(JPAProvider.java:13)
... 6 more
Caused by: org.hibernate.MappingException: Unable to find column with logical name: UID in org.hibernate.mapping.Table(USERS) and its related supertables and secondary tables
at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:552)
at org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:257)
at org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1331)
at org.hibernate.cfg.annotations.CollectionBinder.bindOneToManySecondPass(CollectionBinder.java:791)
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:719)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:668)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:66)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1593)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1350)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1737)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:920)
... 11 more
Person class :
package model.entity;
import model.bl.PersonManager;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
//mapping class to table
#Entity (name = "person")
#Table(name = "USERS")
#EntityListeners(value = PersonManager.class)
public class Person implements Serializable
{
#Id // create id and fill auto by sequence in database
#Column(name="UID" ,columnDefinition = "NUMBER" )
#SequenceGenerator(name = "mySeq" , sequenceName = "DB_MYSEQ")
#GeneratedValue(strategy=GenerationType.AUTO ,generator="mySeq")
private long uId;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "FK_PERSON",referencedColumnName = "UID")
private List<Pictures> picturesList;
#Basic
#Column (name = "USERNAME" , columnDefinition = "NVARCHAR2(30)" , nullable = false , unique = true)
private String username ;
#Basic
#Column (name = "USER_PASSWORD" , columnDefinition = "NVARCHAR2(32)" , nullable = false , unique = true)
private String password ;
#Basic
#Column (name = "EMAIL" , columnDefinition = "NVARCHAR2(40)" , nullable = false)
private String email;
#Basic
#Column (name = "SEX" , columnDefinition = "NVARCHAR2(20)")
private String sex ;
//--------------------------------------------------------
public Person() { }
public Person(String username, String password, String email, String sex, String userPic) {
this.username = username;
this.password = password;
this.email = email;
this.sex = sex;
this.userPic = userPic;
}
public Person(String username, String password, String email ,String sex, String userPic,List<Pictures> picturesList ) {
this.picturesList = picturesList;
this.sex = sex;
this.userPic = userPic;
this.email = email;
this.password = password;
this.username = username;
}
//--------------------------------------------------------
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmail(String email) {
this.email = email;
}
public void setUserPic(String userPic) {
this.userPic = userPic;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setuId(long uId) {this.uId = uId;}
//--------------------------------------------------------
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getUserPic() {
return userPic;
}
public String getEmail() {
return email;
}
public String getSex() {
return sex;
}
public long getuId() {return uId;}
}
}
Pictures class :
package model.entity;
import javax.persistence.*;
import java.io.Serializable;
#Entity(name = "picture")
#Table(name = "PICTURE")
public class Pictures implements Serializable
{
#Id // create id and fill auto by sequence in database
#Column(name="PID" ,columnDefinition = "NUMBER" )
#SequenceGenerator(name = "mySeq2" , sequenceName = "DB_MYSEQ2")
#GeneratedValue(strategy=GenerationType.AUTO ,generator="mySeq2")
private long pId;
#Basic
#Column (name = "PICADRESS" , columnDefinition = "NVARCHAR2(50)" , nullable = false)
private String picAdress ;
#Basic
#Column (name = "CAPTION" , columnDefinition = "LONG")
private String caption;
#Basic // user picture for profile
#Column (name = "LIKES" , columnDefinition = "NUMBER")
private int likes;
//--------------------------------------------------------
public Pictures(){}
public Pictures( String picAdress, String caption, int likes) {
this.picAdress = picAdress;
this.caption = caption;
this.likes = likes;
}
//--------------------------------------------------------
public void setPid(long pid) {
this.pId = pid;
}
public void setLikes(int likes) {
this.likes = likes;
}
public void setPicAdress(String picAdress) {
this.picAdress = picAdress;
}
public void setCaption(String caption) {
this.caption = caption;
}
//--------------------------------------------------------
public int getLikes() {
return likes;
}
public String getCaption() {
return caption;
}
public String getPicAdress() {
return picAdress;
}
public long getPid() {
return pId;
}
}
my JPA Provider is :
public class JPAProvider {
private static final EntityManagerFactory entityManagerFactory;//instate of session for connect to database
static{
entityManagerFactory = Persistence.createEntityManagerFactory("MyConnection");
}
public static EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
}
PersonManager class is :
public class PersonManager {
public static void main(String[] args) {
EntityManager entityManager = JPAProvider.getEntityManagerFactory().createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
Person person = new Person("midas" , "midas123" , "aaaaa#gmail.com", "female" ,"female-user.png" );
Pictures pictures = new Pictures("aaa" , "akflkkglhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh" ,2);
Pictures pictures2 = new Pictures("nnbnbn" , "affddAlllllllllllllllllllllllllllllllllllll" ,5);
List<Pictures> picturesList =new ArrayList<Pictures>();
picturesList.add(pictures);
picturesList.add(pictures2);
person.setPicturesList(picturesList);
entityManager.persist(person);
entityTransaction.commit();
entityManager.close();
}
}
and persistence.xml :
<persistence-unit name="MyConnection" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.connection.username" value="midas"/>
<property name="hibernate.connection.password" value="midas123"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#localhost:1521:orcl"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="show_sql" value="true"></property>
<property name="hibernate.globally_quoted_identifiers" value="true"/>
</properties>
</persistence-unit>
I used the following libraries :
1)hibernate-enverc-4.2.0.final
2)hibernate-jpa-2.0-api-1.0.1-final.jar
3)tomcat library
my JDK version = 1.8.0-172
my IDE = IntellyJ Idea
I use Oracle 11g .
I tried to solve the problem by solving similar questions, but I could not .
for example I checked the following topics that were more similar to my problem :
[Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed
[Getting Exception in thread "main" java.lang.ExceptionInInitializerError Exception
Additional explanation: No tables have been created in the database so far.
Looks like problem is with #JoinColumn(name = "FK_PERSON",referencedColumnName = "UID")
referencedColumnName attribute points to the related column in asociated/referenced entity, i.e. column name of the primary key. By default it is primary key of associated entity. You are not required to fill the referencedColumnName if the referenced entity has single column as PK, because there is no doubt what column it references (i.e. primary key column of associated entity).
change that line to #JoinColumn(name = "FK_PERSON") it should work.
For more info about referencedColumnName refer to "What is referencedColumnName used for in JPA?"

DAO methods all return NullPointerException

I'm developing a little web app for an exam purpose, but I'm encountering several problems with the Dao methods, they all return a NullPointerException.
This is the Façade:
#Stateless(name = "administratorFacade")
public class AdministratorFacade {
#PersistenceContext(unitName = "clinic-unit")
private EntityManager em;
public Administrator getAdministrator(String username){
AdministratorDaoJPA administratorDao = new AdministratorDaoJPA();
Administrator administrator = administratorDao.findByUsername(username);
return administrator;
} //An example of method that uses DAO
This is the DAO:
public class AdministratorDaoJPA implements AdministratorDao {
#PersistenceContext(unitName = "clinic-unit", type = PersistenceContextType.EXTENDED)
private EntityManager em;
#Override
public Administrator findByUsername(String username){
Query query = em.createQuery("SELECT a FROM Administrator a WHERE a.username=?");
return (Administrator)query.setParameter(1,username).getSingleResult();
}
And there is Administrator.java:
#Entity
#NamedQuery(name="allAdministrators", query="SELECT a FROM Administrator a")
public class Administrator {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(unique = true, nullable = false)
private String username;
#Column(nullable = false)
private String name;
#Column(nullable = false)
private String surname;
#Column(nullable = false)
private String pwd;
public Administrator(){}
public Administrator(String username, String name, String surname, String pwd) {
this.username=username;
this.name = name;
this.surname=surname;
this.pwd = pwd;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username ;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return this.pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSurname() {
return surname;
}
public void setSurname(String surName) {
this.surname = surName;
}
#Override
public boolean equals(Object o) {
Administrator adm = (Administrator) o;
return adm.getUsername().equals(this.getUsername());
}
#Override
public int hashCode() {
return this.getUsername().hashCode();
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Adinistrator");
sb.append("{id='").append(id);
sb.append(", name='").append(name);
sb.append(", surname='").append(surname);
sb.append(", username='").append(username);
sb.append("}\n");
return sb.toString();
}
}
And finally the persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="clinic-unit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>PostgreSQL Database</jta-data-source>
<class>it.clinic.model.Indicator</class>
<class>it.clinic.model.Administrator</class>
<class>it.clinic.model.Exam</class>
<class>it.clinic.model.ExamTypology</class>
<class>it.clinic.model.Medic</class>
<class>it.clinic.model.Patient</class>
<class>it.clinic.model.Prerequisite</class>
<properties>
<!-- ad ogni esecuzione viene creato lo schema, cancellando il contenuto delle tabelle
<property name="hibernate.hbm2ddl.auto" value="create"/> -->
<!-- SQL dialect -->
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<!--- Per avere info sulle istruzioni SQL inviate al db -->
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.archive.autodetection" value="class"/>
</properties>
</persistence-unit>
</persistence>
Stacktrace:
java.lang.NullPointerException
it.clinic.persistence.ExamTypologyDaoJPA.findAll(ExamTypologyDaoJPA.java:54)
it.clinic.facade.AdministratorFacade.getAllExamTypologies(AdministratorFacade.java:53)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:100)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:236)
org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:203)
org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbObjectProxyHandler.java:265)
org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:260)
org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:89)
org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:347)
it.clinic.facade.AdministratorFacade$$LocalBeanProxy.getAllExamTypologies(it/clinic/facade/AdministratorFacade.java)
it.clinic.controller.ExamTypologyController.examTypologiesList(ExamTypologyController.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.tomee.catalina.JavaeeInstanceManager.postConstruct(JavaeeInstanceManager.java:163)
org.apache.tomee.mojarra.TomEEInjectionProvider.invokePostConstruct(TomEEInjectionProvider.java:57)
com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:221)
com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:103)
com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:257)
com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:117)
com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
com.sun.faces.el.ChainTypeCompositeELResolver.getValue(ChainTypeCompositeELResolver.java:90)
org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:96)
org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:80)
org.apache.el.parser.AstValue.getValue(AstValue.java:137)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:115)
org.apache.taglibs.standard.tag.common.core.ForEachSupport.prepare(ForEachSupport.java:151)
javax.servlet.jsp.jstl.core.LoopTagSupport.doStartTag(LoopTagSupport.java:256)
org.apache.jsp.ExamTypologies_jsp._jspx_meth_c_005fforEach_005f0(ExamTypologies_jsp.java:280)
org.apache.jsp.ExamTypologies_jsp._jspService(ExamTypologies_jsp.java:232)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:642)
com.sun.faces.application.view.JspViewHandlingStrategy.executePageToBuildView(JspViewHandlingStrategy.java:363)
com.sun.faces.application.view.JspViewHandlingStrategy.buildView(JspViewHandlingStrategy.java:153)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:99)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.openejb.server.httpd.WebBeansFilter.doFilter(WebBeansFilter.java:52)
I'm using JPA with Tomee and JSF 2.2.
I hope you will help me to go through this :)
You're using
new AdministratorDaoJPA()
to get your DAO. So the container can't inject anything into that object, and the entityManager field thus has its default value: null.
For injection to happen, you must let the container create and inject the objects.
You also don't need the entity manager in your facade, so there is no point in injecting it there. What you need to inject is the DAO:
#Inject
private AdministratorDaoJPA administratorDao;

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 can't access PostgreSQL due to cast problems

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.

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