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'.
Related
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.
This question What is the right way to use entitymanager
supplied a link to EntityManagerHelper.java which I added to my code base. When I use this helper class to make subsequent calls to the database it returns previous results to the same query.
The scenario I see this most in is retrieving the lastentry property of my User Class. On the browser I make an AJAX request and the servlet partial below gets the user object and calls a method to return my lastentry.
I've read about .clear() but I get server errors when I added it to my EntityManagerHelper. I would like to avoid creating an EntityManager every time I want to make a call to the db.
How can I fix this problem?
partial from servlet
User user = User.getUser();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(user.getLastentry());
User Class
package entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Persistence;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.shiro.SecurityUtils;
import responseablees.EntityManagerHelper;
/**
*
* #author Christopher Loughnane <chrisloughnane1#gmail.com>
*/
#Entity
#Table(name = "user")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
, #NamedQuery(name = "User.findById", query = "SELECT u FROM User u WHERE u.id = :id")
, #NamedQuery(name = "User.findByUsername", query = "SELECT u FROM User u WHERE u.username = :username")
, #NamedQuery(name = "User.getUsernameByUserEmail", query = "SELECT u.username FROM User u WHERE u.useremail = :useremail")
, #NamedQuery(name = "User.findByUserEmail", query = "SELECT u FROM User u WHERE u.useremail = :useremail")
, #NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password")})
public class User implements Serializable {
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 2048)
#Column(name = "lastentry")
private String lastentry;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 128)
#Column(name = "useremail")
private String useremail;
#Basic(optional = false)
#Column(name="created", insertable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
private Date created;
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 = 100)
#Column(name = "username")
private String username;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "password")
private String password;
public User() {
}
public User(Integer id) {
this.id = id;
}
public User(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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#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 User)) {
return false;
}
User other = (User) 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 "DAOs.User[ id=" + id + " ]";
}
public String getUseremail() {
return useremail;
}
public void setUseremail(String useremail) {
this.useremail = useremail;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getLastentry() {
return lastentry;
}
public void setLastentry(String lastentry) {
this.lastentry = lastentry;
}
public static User getUser(){
String currentUser = (String) SecurityUtils.getSubject().getPrincipal();
User user = (User) em.createNamedQuery("User.findByUserEmail")
.setParameter("useremail", currentUser)
.getSingleResult();
return user;
}
}
Requested Code
Verbose Approach
String currentUser = (String) SecurityUtils.getSubject().getPrincipal();
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("com.mycompany_responseableES_war_1.0-SNAPSHOTPU");
EntityManager em = emfactory.createEntityManager();
User user = (User) em.createNamedQuery("User.findByUserEmail")
.setParameter("useremail", currentUser)
.getSingleResult();
em.getTransaction().begin();
user.setLastentry(JSON);
em.getTransaction().commit();
EntityManagerHelper Approach
User user = User.getUser();
EntityManager em = EntityManagerHelper.getEntityManager();
em.getTransaction().begin();
user.setLastentry(JSON);
em.getTransaction().commit();
First of all, I would be careful to put ALL my data fetching/modification code between
em.getTransaction().begin()
and
em.getTransaction().commit()
This ensures that your entities are managed and your changes are automatically persisted. In your code it looks like the User instance comes from outside the transaction. I have not worked much with JPA and manual transactions, but I would not be surprised if the user is detached (that is, not managed by the EntityManager) and so changes are not automatically persisted to the database. If that were the case I guess you could solve it by putting
// merge(...) takes an entity that is not managed, apply changes to
// the persistence context and returns a new *managed* entity.
// The original entity REMAINS *detached* or *non persistent*
User managedUser = em.merge(user);
// I assume that you have something like this to set your user in the
// current session or whatever
User.setUser(managedUser);
just before the commit.
JPA vocabulary can be a bit hard at first, read this for more details about the JPA entity lifecycle (specially the diagram at the bottom).
I have the following problem, in my application I would like to have some kind of login. I have following code: (Inspiration here on the web)
public boolean login(String username, String password)
{
try{
EntityTransaction entr=em.getTransaction();
entr.begin();
TypedQuery<Users> query = em.createQuery("SELECT u FROM users u WHERE u.login = :login AND u.password = :pass", Users.class);
query.setParameter(1, username);
query.setParameter(2, password);
try{
Users u = query.getSingleResult();
return true;
}catch(javax.persistence.NoResultException e)
{
return false;
}
}
finally{
em.close();
}
}
When I run it and try to log in, the console will write the following message:
exception in thread "main" java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Problem compiling [SELECT u FROM users u WHERE u.login = :login AND u.password = :pass].
[14, 19] The abstract schema type 'users' is unknown.
[28, 35] The state field path 'u.login' cannot be resolved to a valid type.
[49, 59] The state field path 'u.password' cannot be resolved to a valid type.
This is my table:
/*
* 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 com.dke.ps.Tables;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author michal
*/
#Entity
#Table(name = "users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u")
, #NamedQuery(name = "Users.findByUserid", query = "SELECT u FROM Users u WHERE u.userid = :userid")
, #NamedQuery(name = "Users.findByLogin", query = "SELECT u FROM Users u WHERE u.login = :login")
, #NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password = :password")
, #NamedQuery(name = "Users.findByEmail", query = "SELECT u FROM Users u WHERE u.email = :email")
, #NamedQuery(name = "Users.findByDate", query = "SELECT u FROM Users u WHERE u.date = :date")})
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "userid")
private Integer userid;
#Column(name = "login")
private String login;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Column(name = "date")
#Temporal(TemporalType.DATE)
private Date date;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userid")
private Collection<Saves> savesCollection;
#JoinColumn(name = "saveid", referencedColumnName = "saveid")
#ManyToOne
private Saves saveid;
public Users() {
}
public Users(Integer userid) {
this.userid = userid;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
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 Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#XmlTransient
public Collection<Saves> getSavesCollection() {
return savesCollection;
}
public void setSavesCollection(Collection<Saves> savesCollection) {
this.savesCollection = savesCollection;
}
public Saves getSaveid() {
return saveid;
}
public void setSaveid(Saves saveid) {
this.saveid = saveid;
}
#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 Users)) {
return false;
}
Users other = (Users) 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 "com.dke.ps.Tables.Users[ userid=" + userid + " ]";
}
}
As you can see, the "users" table really exists. I have no idea why it says to me, "The abstract schema type 'users' is unknown.".
Can you help me? I think the other two errors are caused by the first one.
This exception relates to JPQL query compiling, JPQL syntax expect entity names instead table names, try changing your query to the following:
SELECT u FROM **Users** u WHERE u.login = :login AND u.password = :pass
Entity class:
package com.rapid.admin.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* LoginHistory entity. #author MyEclipse Persistence Tools
*/
#Entity
#Table(name = "login_history", catalog = "project")
public class LoginHistory implements java.io.Serializable {
// Fields
private Integer id;
private String username;
private Timestamp loginTime;
private Timestamp logoutTime;
private Boolean status;
private String timeId;
// Constructors
/** default constructor */
public LoginHistory() {
}
/** full constructor */
public LoginHistory(String username, Timestamp loginTime,
Timestamp logoutTime, Boolean status, String timeId) {
this.username = username;
this.loginTime = loginTime;
this.logoutTime = logoutTime;
this.status = status;
this.timeId = timeId;
}
// Property accessors
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "username", length = 45)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "login_time", length = 19)
public Timestamp getLoginTime() {
return this.loginTime;
}
public void setLoginTime(Timestamp loginTime) {
this.loginTime = loginTime;
}
#Column(name = "logout_time", length = 19, updatable= true)
public Timestamp getLogoutTime() {
return this.logoutTime;
}
public void setLogoutTime(Timestamp logoutTime) {
this.logoutTime = logoutTime;
}
#Column(name = "status")
public Boolean getStatus() {
return this.status;
}
public void setStatus(Boolean status) {
this.status = status;
}
#Column(name = "time_id", length = 45)
public String getTimeId() {
return this.timeId;
}
public void setTimeId(String timeId) {
this.timeId = timeId;
}
Hibernate query :
sessionFactory.getCurrentSession().beginTransaction();
Criteria criteria =
sessionFactory.getCurrentSession().createCriteria(LoginHistory.class);
criteria.add(Restrictions.eq("id",id));
LoginHistory loginHistory = new LoginHistory();
loginHistory.setLogoutTime(AdminUtil.getTimeStamp());
sessionFactory.getCurrentSession().update(loginHistory);
Error on console:
org.hibernate.TransientObjectException: The given object has a null identifier: com.rapid.admin.entity.LoginHistory
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.getUpdateId(DefaultSaveOrUpdateEventListener.java:272)
at org.hibernate.event.def.DefaultUpdateEventListener.getUpdateId(DefaultUpdateEventListener.java:69)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:240)
at org.hibernate.event.def.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireUpdate(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:580)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:572)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:342)
at $Proxy21.update(Unknown Source)
at com.rapid.admin.daoimpl.LoginDaoImpl.updateLogoutTime(LoginDaoImpl.java:117)
at com.rapid.admin.serviceimpl.LoginServiceImpl.updateLogoutTime(LoginServiceImpl.java:53)
at com.rapid.admin.controller.LoginController.logout(LoginController.java:87)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
org.hibernate.TransientObjectException: The given object has a null identifier: com.rapid.admin.entity.LoginHistory
I guess you should write like this : (by considering you want to update LoginHistory which is already in DB having id that you are passing)
hibernate query :
sessionFactory.getCurrentSession().beginTransaction();
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(LoginHistory.class);
criteria.add(Restrictions.eq("id",id));
LoginHistory loginHistory = (LoginHistory)criteria.uniqueResult();
loginHistory.setLogoutTime(AdminUtil.getTimeStamp());
sessionFactory.getCurrentSession().update(loginHistory);
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.