jpa select new with embedded key throws exception - jpa

I am getting an exception when trying to run the following named query
#NamedQuery(name = "software.listAssemblies", query = "SELECT distinct NEW com.blackbox.dao.AssemblyToBootloaderDTO(s.id.assemblyId, s.filename) FROM Software s where s.id.platformId = :platformId and s.id.txaddress = :txaddress and s.filetype = 'SBL';")
If I remove the reference to the AssemblyToBootloaderDTO so the query reads
#NamedQuery(name = "software.listAssemblies", query = "SELECT distinct s.id.assemblyId, s.filename FROM Software s where s.id.platformId = :platformId and s.id.txaddress = :txaddress and s.filetype = 'SBL';")
then the query runs successfully returning a list of object[] as expected.
I have several named queries in my app that create DTO objects via SELECT NEW that run without a problem, but this is the first one I've tried where I'm using a field from an embedded key in the DTO so I'm guessing that I'm missing some syntax here. What do I need to do to get the mapping to the DTO class work?
#Entity
#Table(name="software")
#NamedQueries({
#NamedQuery(name = "software.listBootLoaders", query = "SELECT distinct s.filename FROM Software s where s.id.platformId = :platformId and s.id.txaddress = :txaddress and s.filetype = 'SBL';"),
#NamedQuery(name = "software.listAssemblies", query = "SELECT distinct NEW com.blackbox.dao.AssemblyToBootloaderDTO(s.id.assemblyId, s.filename) FROM Software s where s.id.platformId = :platformId and s.id.txaddress = :txaddress and s.filetype = 'SBL';")
})
public class Software implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private SoftwarePK id;
#Column(name="fileName", length=32)
private String filename;
#Column(name="fileType", length=8)
private String filetype;
#Column(name="predecessor", length=64)
private String predecessor;
#Column(name="successor", length=64)
private String successor;
//bi-directional many-to-one association to Hardware
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumns({
#JoinColumn(name="assemblyId", referencedColumnName="assemblyId", nullable=false, insertable=false, updatable=false),
#JoinColumn(name="busId", referencedColumnName="busId", nullable=false, insertable=false, updatable=false),
#JoinColumn(name="hardwareId", referencedColumnName="hardwareId", nullable=false, insertable=false, updatable=false),
#JoinColumn(name="platformId", referencedColumnName="platformId", nullable=false, insertable=false, updatable=false),
#JoinColumn(name="txAddress", referencedColumnName="txAddress", nullable=false, insertable=false, updatable=false)
})
private Hardware hardware;
public Software() {
}
public SoftwarePK getId() {
return this.id;
}
public void setId(SoftwarePK id) {
this.id = id;
}
... getters/setters omitted
The embedded key;
#Embeddable
public class SoftwarePK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name="platformId",unique=true, nullable=false)
private int platformId;
#Column(name="busId", unique=true, nullable=false)
private int busid;
#Column(name="txAddress", unique=true, nullable=false, length=3)
private String txaddress;
#Column(name="assemblyId",unique=true, nullable=false, length=64)
private String assemblyId;
#Column(name="hardwareId",unique=true, nullable=false, length=64)
private String hardwareId;
#Column(name="sequence",unique=true, nullable=false)
private int sequence;
#Column(name="softwareId",unique=true, nullable=false, length=64)
private String softwareId;
public SoftwarePK() {
}
getters/setters omitted.
The DTO;
public class AssemblyToBootloaderDTO {
private String assemblyId;
private String softwareBootloaderId;
public AssemblyToBootloaderDTO(String assemblyId,
String softwareBootloaderId) {
this.assemblyId = assemblyId;
this.softwareBootloaderId = softwareBootloaderId;
}
public String getAssemblyId() {
return assemblyId;
}
public String getSoftwareBootloaderId() {
return softwareBootloaderId;
}
}
and the exception;
Exception [EclipseLink-6052] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.QueryException
Exception Description: An outer join (getAllowingNull or anyOfAllowingNone) is only valid for OneToOne, OneToMany, ManyToMany, AggregateCollection and DirectCollection Mappings, and cannot be used for the mapping [org.eclipse.persistence.mappings.DirectToFieldMapping[assemblyId-->software.assemblyId]].
org.eclipse.persistence.exceptions.QueryException.outerJoinIsOnlyValidForOneToOneMappings(QueryException.java:924)
org.eclipse.persistence.internal.expressions.QueryKeyExpression.validateNode(QueryKeyExpression.java:863)
org.eclipse.persistence.expressions.Expression.normalize(Expression.java:3009)
org.eclipse.persistence.internal.expressions.DataExpression.normalize(DataExpression.java:342)
org.eclipse.persistence.internal.expressions.QueryKeyExpression.normalize(QueryKeyExpression.java:612)
org.eclipse.persistence.internal.expressions.QueryKeyExpression.normalize(QueryKeyExpression.java:599)
org.eclipse.persistence.internal.expressions.SQLSelectStatement.normalize(SQLSelectStatement.java:1311)
org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.buildReportQuerySelectStatement(ExpressionQueryMechanism.java:560)
org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.buildReportQuerySelectStatement(ExpressionQueryMechanism.java:506)
org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.prepareReportQuerySelectAllRows(ExpressionQueryMechanism.java:1527)
org.eclipse.persistence.queries.ReportQuery.prepareSelectAllRows(ReportQuery.java:1298)
org.eclipse.persistence.queries.ReadAllQuery.prepare(ReadAllQuery.java:625)
org.eclipse.persistence.queries.ReportQuery.prepare(ReportQuery.java:1047)
org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:509)
org.eclipse.persistence.queries.ObjectLevelReadQuery.checkPrepare(ObjectLevelReadQuery.java:820)
org.eclipse.persistence.queries.DatabaseQuery.prepareCall(DatabaseQuery.java:1588)
org.eclipse.persistence.internal.jpa.EJBQueryImpl.getDatabaseQueryInternal(EJBQueryImpl.java:568)
org.eclipse.persistence.internal.jpa.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:1001)
com.blackbox.dao.JpaSoftwareDao.listAssemblies(JpaSoftwareDao.java:168)
com.blackbox.services.Services.getAssemblyNames(Services.java:571)
com.blackbox.genesis.ccfeditor.services.NanocomService.buildSource(NanocomService.java:48)
com.blackbox.genesis.actions.ccfedit.DownloadCCForNanocom.execute(DownloadCCForNanocom.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254)
com.blackbox.x.interceptors.LicenseInterceptor.intercept(LicenseInterceptor.java:75)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:142)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:166)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.blackbox.x.interceptors.Log4jMDCInterceptor.intercept(Log4jMDCInterceptor.java:51)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.blackbox.x.interceptors.RedirectMessageInterceptor.doIntercept(RedirectMessageInterceptor.java:78)
com.blackbox.x.interceptors.RedirectMessageInterceptor.intercept(RedirectMessageInterceptor.java:63)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter.doFilter(StrutsExecuteFilter.java:88)
com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)
com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter.doFilter(StrutsPrepareFilter.java:82)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)

Seems to be a jpa/implementation bug, I am running eclipselink 2.3 and get the same issue.
As alternative, remove #Embeddable and #EmbeddedId and use #IdClass on entity level instead with #Id on your key fields i.e:
#Table(name = "MY_TABLE")
#IdClass(value=MyTableId.class)
public class MyTableEntity implements Serializable {
private static final long serialVersionUID = 1000L;
public static class MyTableId implements Serializable {
private static final long serialVersionUID = 1000L;
private Integer keyFieldOne;
private String keyFieldTwo;
public MyTableId() {
super();
}
public MyTableId(Integer keyFieldOne, String keyFieldTwo) {
this.keyFieldOne = keyFieldOne;
this.keyFieldTwo = keyFieldTwo;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MyTableId myTableId = (MyTableId)obj;
return Objects.equal(keyFieldOne, myTableId.keyFieldOne) && Objects.equal(keyFieldTwo, myTableId.keyFieldTwo);
}
#Override
public int hashCode() {
return Objects.hashCode(keyFieldOne, keyFieldTwo);
}
}
#Id
#Column(name = "KEY_FIELD_ONE", nullable = false)
private Integer keyFieldOne;
#Id
#Column(name = "KEY_FIELD_TWO", nullable = false, length = 8)
private String keyFieldTwo;
...
}
Note I used google guava for hash code and equals overrides

Seems to be an issue with the join inside the constructor element.
Try the latest/2.4 release, I would guess this has been fixed. If still not luck, please log a bug.

Related

NullPointerException is occurring with createNamedQuery and then persistence unit logins successfully

I can't seem to solve this issue. I have tried googling but can't put the pieces together to solve it. I have the following stack trace:
Warning: java.lang.NullPointerException
at org.eclipse.persistence.platform.server.ServerPlatformUtils.createServerPlatform(ServerPlatformUtils.java:99)
at org.eclipse.persistence.sessions.factories.SessionManager.init(SessionManager.java:77)
at org.eclipse.persistence.sessions.factories.SessionManager.<clinit>(SessionManager.java:71)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.addSessionToGlobalSessionManager(EntityManagerSetupImpl.java:907)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.initSession(EntityManagerSetupImpl.java:2671)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:675)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:205)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:305)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:337)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:318)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:197)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createNamedQuery(EntityManagerWrapper.java:521)
at session.CategoryFacade.findRandom(CategoryFacade.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.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:64)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
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.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:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
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.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy173.findRandom(Unknown Source)
at session.__EJB31_Generated__CategoryFacade__Intf____Bean__.findRandom(Unknown Source)
at actions.ActionFacade.setFeaturedCategories(ActionFacade.java:82)
at actions.HomeAction.execute(HomeAction.java:16)
at controller.ControllerServlet.service(ControllerServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Info: EclipseLink, version: Eclipse Persistence Services - 2.6.1.v20150605-31e8258
Info: /file:/Users/csexton/NetBeansProjects/ReadersParadise/build/web/WEB-INF/classes/_AffableBeanPU login successful
So if you look at the last two lines my persistent unit isn't logging in until I try to use the entity manager. If I do another query after the first one, everything is good, no errors, nothing......Error occurs on the createNamedQuery. The query exists and matches the exact name. I can call the same method twice and the first one causes a NPE but the second one works fine.
#Stateless(name="CategoryFacade")
public class CategoryFacade extends AbstractFacade<Category> {
#PersistenceContext(unitName = "AffableBeanPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public CategoryFacade() {
super(Category.class);
}
public List<Category> findRandom(int limit) {
return getEntityManager()
.createNamedQuery("Category.findRandomByLimit")
.setParameter(1, limit)
.getResultList();
}
}
I am doing a jndi lookup for the class
public class ActionFacade implements AutoCloseable {
private static ThreadLocal<ActionFacade> instance = new ThreadLocal<>();
private HttpServletRequest request;
private HttpSession session;
private CategoryFacade categoryFacade;
private BookFacade bookFacade;
private OrderManager orderManager;
private ShoppingCart cart;
public ActionFacade(HttpServletRequest request) {
this.request = request;
this.session = request.getSession();
try {
Context ctx = new InitialContext();
this.categoryFacade = (CategoryFacade) ctx.lookup(
"java:global/ReadersParadise/CategoryFacade!session.CategoryFacade");
System.out.print("JNDI lookup complete.");
this.bookFacade = (BookFacade) ctx.lookup(
"java:global/ReadersParadise/BookFacade!session.BookFacade");
this.orderManager = (OrderManager) ctx.lookup(
"java:global/ReadersParadise/OrderManager!session.OrderManager");
} catch (NamingException ex) {
System.err.println(ex);
}
}
public static ActionFacade create(HttpServletRequest request) {
ActionFacade facade = new ActionFacade(request);
instance.set(facade);
return facade;
}
public static ActionFacade getCurrentInstance() {
return instance.get();
}
#Override
public void close() {
instance.remove();
}
public void setSelectedCategory() {
String categoryName = request.getParameter("category");
Category selectedCategory = categoryFacade.findByName(categoryName);
if (selectedCategory == null) {
selectedCategory = categoryFacade.find(1);
}
session.setAttribute("selectedCategory", selectedCategory);
Collection<Book> categoryBooks = selectedCategory.getBookCollection();
session.setAttribute("categoryBooks", categoryBooks);
}
public void setAllCategories() {
request.setAttribute("categories", categoryFacade.findAll());
}
}
Then in my servlet I am using the ActionFacade like this....
try(ActionFacade facade = ActionFacade.create(request)) {
Action action = ActionFactory.getAction(request);
String view = action.execute(facade);
System.out.println(request.getServletPath());
if (request.getServletPath().equals("") || view.equals(request.getServletPath().substring(1))) {
request.getRequestDispatcher("/WEB-INF/views/" + view + ".jsp").forward(request, response);
} else {
response.sendRedirect(view);
}
} catch (NullPointerException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (Exception e) {
throw new ServletException("Executing action failed.", e);
}
This is the category entity
#Entity
#Table(name = "category")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"),
#NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id"),
#NamedQuery(name = "Category.findByName", query = "SELECT c FROM Category c WHERE c.name= :name")
})
#NamedNativeQuery(name = "Category.findRandomByLimit",
query = "SELECT * FROM Category ORDER BY RAND() LIMIT ?1")
public class Category 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 = 45)
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private Collection<Book> bookCollection;
public Category() {
}
public Category(Integer id) {
this.id = id;
}
public Category(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlTransient
public Collection<Book> getBookCollection() {
return bookCollection;
}
public void setBookCollection(Collection<Book> bookCollection) {
this.bookCollection = bookCollection;
}
#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 Category)) {
return false;
}
Category other = (Category) 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.Category[ id=" + id + " ]";
}
}
Category Action Class which uses the ActionFacade
public class CategoryAction implements Action {
#Override
public String execute(ActionFacade facade) throws Exception {
facade.setSelectedCategory();
facade.setAllCategories();
return "category";
}
}
I think it is a problem of Glassfish 4.1.1 described here:
https://java.net/jira/browse/GLASSFISH-21468
According this, it may help, if you add
<property name="eclipselink.target-server" value="Glassfish"/>
to your persistence.xml

Null pointer exception when calling JPA named query

I know there are many questions like this here but I've looked at tons and still haven't been able to solve my problem.
I am trying call a named query. I have the following:
#Stateless
public class ClientCFacade extends AbstractFacade<ClientC> {
#PersistenceContext(unitName = "the_database")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public ClientCFacade() {
super(ClientC.class);
}
public List<ClientC> findByClientId(Integer clientId) {
try {
List<ClientC> clientCsList = em.createNamedQuery(ClientCs.FIND_BY_CLIENT_ID, ClientC.class).
setParameter("clientId", clientId)
.getResultList();
return clientCsList;
} catch (NoResultException ex) {
return null;
}
}
and
#Entity
#Table(name = "clients")
#NamedQueries({
#NamedQuery(name = ClientCs.FIND_BY_CLIENT_ID,
query = "select cc" +
"from " +
"ClientCs cc " +
"WHERE " +
"cc.clientId= :clientId")
})
public class ClientCs implements Serializable {
private static final long serialVersionUID = 1L;
public static final String FIND_BY_CLIENT_ID = "ClientCs.findByClientId";
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "client_id", nullable = false)
private Integer clientId;
with all the getters and setters.
And I call it like:
List<ClientC> Cs = clientCFacade.findByClientId(1234);
My error is:
java.lang.NullPointerException
at the.package.name.ClientCFacade.findByClientId(ClientCFacade.java:56)
at the.package.name.service.ApiService.runTransaction(ApiService.java:413)
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:483)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:745)
Any help is seriously appreciated.
You're setting a parameter which doesn't exist in your named query.
Replace id with clientId in the method public List<ClientC> findByClientId(String clientId)
It should look like this:
List<ClientC> clientCsList = em.createNamedQuery(ClientCs.FIND_BY_CLIENT_ID, ClientC.class).
setParameter("clientId", clientId)
.getResultList();

getIdentifier method of PersistenceUnitUtil not working for Composite keys

I am getting below error when trying to retrieve identity using getIdentifier method of PersistenceUnitUtil. Is there anything I am doing wrong.
Local Exception Stack:
Exception [EclipseLink-0] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: An internal error occurred accessing the primary key object [202].
Internal Exception: java.lang.NullPointerException
Descriptor: RelationalDescriptor(com.sample.Person --> [DatabaseTable(PERSON)])
at org.eclipse.persistence.exceptions.DescriptorException.errorUsingPrimaryKey(DescriptorException.java:1923)
at org.eclipse.persistence.internal.jpa.CMP3Policy$FieldAccessor.setValue(CMP3Policy.java:686)
at org.eclipse.persistence.descriptors.CMPPolicy.createPrimaryKeyInstance(CMPPolicy.java:453)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getIdentifier(EntityManagerFactoryImpl.java:75)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getIdentifier(EntityManagerFactoryDelegate.java:679)
at com.sample.PersistenceUtil.getEntityIdentifier(PersistenceUtil.java:27)
at com.sample.PersistenceUtil.getEntityIdentifier(PersistenceUtil.java:18)
at com.sample.OverrideUtilTest.canconfirmEntityEqualsforCompositeId2(OverrideUtilTest.java:147)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.NullPointerException
at org.eclipse.persistence.internal.jpa.CMP3Policy$FieldAccessor.setValue(CMP3Policy.java:682)
... 29 more
The code sample I am trying is this:
#Entity
#IdClass(PersonPK.class)
#Table(name = "PERSON")
public class Person {
#Id
#Column(name = "CODE_C")
private String code;
#Column(name = "NAME_C")
private String name;
#Id
#Column(name = "COUNTRY_C")
private String country;
public Person() {
}
public Person(String code, String country) {
this.code = code;
this.country = country;
}
public String getCode() {
return this.code;
}
public String getCountry() {
return this.country;
}
}
public class PersonPK implements Serializable {
private static final long serialVersionUID = 1L;
private final String code;
private final String country;
public PersonPK(String city, String country) {
super();
this.code = city;
this.country = country;
}
#Override
public boolean equals(Object object) {
return super.equals (object);
}
#Override
public int hashCode() {
return super.hashCode();
}
}
The code to retrieve identity I am using is
getEntityManagerFactory(persistenceUnitName).getPersistenceUnitUtil()
.getIdentifier(entity);
Any help is appreciated
The primary key class must be public and must have a public no-arg constructor.
Hibernate message in similar situation is a little bit more informative
javax.persistence.PersistenceException: org.hibernate.InstantiationException: No default constructor for entity: : PersonPK
Solution: Add default constructor to PersonPK

getting NullPointerException when try to persist entity

I have the following code. When I run the junit test it's creating a table and fields but they are null. I'm also getting a NullPointerException..
Why isn't my user being added?
java.lang.NullPointerException
at com.testproject.repo.JPAUserRepo.addUser(JPAUserRepo.java:15)
at com.testproject.manager.UserManager.saveUser(UserManager.java:18)
at com.testproject.manager.test.UserManagerTest.testSaveUser(UserManagerTest.java:44)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
User.java
#Entity
#Table(name="USER")
#NamedQuery(name="getAllUser", query="SELECT a FROM User a ORDER BY a.userid")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="USER_ID")
private long userid;
#Column(name="USERNAME")
private String username;
#Column(name="PASSWORD")
private String password;
#Column(name="USER_EMAIL")
private String userEmail;
#Column(name="USER_PHONE")
private int userPhone;
public User() {
// TODO Auto-generated constructor stub
}
public User(String username, String password, String email, int userPhone) {
super();
this.username = username;
this.password = password;
this.userEmail = email;
this.userPhone = userPhone;
}
//Getters and Setters
JPAUserRepo.java
public class JPAUserRepo implements UserRepo {
EntityManager em;
#Override
public void addUser(User user) {
em.persist(user);
}
UserManager.java
public class UserManager {
UserRepo userRepo;
public void saveUser(User user){
userRepo.addUser(user);
}
UserManagerTest.java
public class UserManagerTest {
EntityManager em;
UserManager userManager;
User user;
#Before
public void setUp() throws Exception {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnitMySQL");
em = factory.createEntityManager();
userManager = new UserManager();
JPAUserRepo jpaUserRepo = new JPAUserRepo();
userManager.setUserRepo(jpaUserRepo);
em.getTransaction().begin();
user = new User("name", "password", "mail#mail.com", 1561234567);
}
#After
public void tearDown() throws Exception {
em.getTransaction().commit();
}
#Test
public void testSaveUser() {
userManager.saveUser(user);
}
}

Persistence of a triple association when adding Spring transactions

I have a Java EE application using JPA (EclipseLink) and Spring framework.
Everything worked fine in my persistence classes until I added Spring transaction management.
I have following entities (corresponding to the database tables) :
Project
#Entity
#Table(name="projet")
public class Projet implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_projet", unique=true, nullable=false)
private Integer idProjet;
#Column(name="nom_projet")
private String nomProjet;
/** The projet util droits. */
#OneToMany(mappedBy="projet", cascade={CascadeType.ALL})
private Set<ProjetUtilDroit> projetUtilDroits;
public Projet() {
}
...
}
User
#Entity
#Table(name="utilisateur")
public class Utilisateur implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The id utilisateur. */
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_utilisateur", unique=true, nullable=false)
private Integer idUtilisateur;
/** The nom utilisateur. */
#Column(name="nom_utilisateur", nullable=false, length=50)
private String nomUtilisateur;
//bi-directional many-to-one association to ProjetUtilDroit
/** The projet util droits. */
#OneToMany(mappedBy="utilisateur", cascade={CascadeType.REMOVE})
private Set<ProjetUtilDroit> projetUtilDroits;
...
}
Right
#Entity
#Table(name="droit")
public class Droit implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The id droit. */
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_droit", unique=true, nullable=false)
private Integer idDroit;
/** The type droit. */
#Column(name="type_droit", nullable=false, length=10)
private String typeDroit;
/**
* Instantiates a new droit.
*/
public Droit() {
}
...
}
And an association which links a user to a project with a specific right (ProjectUserRight)
#Entity
#Table(name="projet_util_droit")
public class ProjetUtilDroit implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The id. */
#EmbeddedId
private ProjetUtilDroitPK id;
//bi-directional many-to-one association to Droit
/** The droit. */
#ManyToOne(cascade={CascadeType.MERGE, CascadeType.REFRESH})
#JoinColumn(name="id_droit")
private Droit droit;
//bi-directional many-to-one association to Projet
/** The projet. */
#MapsId("idProjet")
#ManyToOne(cascade={CascadeType.MERGE, CascadeType.REFRESH})
#JoinColumn(name="id_projet")
private Projet projet;
//bi-directional many-to-one association to Utilisateur
/** The utilisateur. */
#MapsId("idUtilisateur")
#ManyToOne(cascade={CascadeType.MERGE, CascadeType.REFRESH})
#JoinColumn(name="id_utilisateur")
private Utilisateur utilisateur;
...
}
The embedded id for the association:
#Embeddable
public class ProjetUtilDroitPK implements Serializable {
//default serial version id, required for serializable classes.
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The id projet. */
#Column(name="id_projet", unique=true, nullable=false)
private Integer idProjet;
/** The id utilisateur. */
#Column(name="id_utilisateur", unique=true, nullable=false)
private Integer idUtilisateur;
...
}
My method creating the project with its right:
public Projet createProject(String name, int idRight, int idUser) {
Projet project = new Projet();
project.setNomProjet(name);
ProjetUtilDroit pud = new ProjetUtilDroit();
Droit d = rightDao.findById(idRight);
pud.setDroit(d);
pud.setProjet(project);
Utilisateur user = userDao.findById(idUser);
pud.setUtilisateur(user);
if(user.getProjetUtilDroits() == null)
user.setProjetUtilDroits(new HashSet<ProjetUtilDroit>());
user.getProjetUtilDroits().add(pud);
Set<ProjetUtilDroit> pudSet = new HashSet<ProjetUtilDroit>();
pudSet.add(pud);
project.setProjetUtilDroits(pudSet);
project = projectDao.create(project);
return project;
}
It worked like a charm (persist the project and the associated user rights) until I add the annotation #Transactionnal above the "createProject" method...
Now I get this error:
Avertissement: StandardWrapperValve[dispatcher]: PWC1406: Servlet.service() for servlet dispatcher threw exception
java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST:
*****Project right****
User name: userName Right: read.
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.discoverUnregisteredNewObjects(RepeatableWriteUnitOfWork.java:304)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.calculateChanges(UnitOfWorkImpl.java:702)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.writeChanges(RepeatableWriteUnitOfWork.java:433)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:780)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.performPreQueryFlush(EJBQueryImpl.java:1298)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:434)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getResultList(EJBQueryImpl.java:742)
at com.dao.BasicDAO.findAll(BasicDAO.java:92)
at com.dao.BasicDAO.create(BasicDAO.java:103)
at com.services.ProjectService.createProject(ProjectService.java:48)
at com.services.ProjectService$$FastClassByCGLIB$$67c85b9f.invoke()
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at com.services.ProjectService$$EnhancerByCGLIB$$398fa756.createProject()
at com.servlet.Test.handleCreateProject(Test.java:31)
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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
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:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
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:668)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
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:849)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
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:722)
The only solution I imagine is to create the project within one transaction and save its rights separately within another transaction. Is that the only solution or does anybody have another suggestion?
Which object was not persisted? Include the full exception.
You need to either mark the relationship to the object as cascade persist, or call persist on the object before persisting the project.