I am developing a JSF application with Netbeans and Glassfish. When I change something and Netbeans redeploys to Glassfish, then a ClassCastException is been thrown on the entity class itself.
Caused by: java.lang.ClassCastException: com.twibu.entity.Tipper cannot be cast to com.twibu.entity.Tipper
at com.twibu.service.TipperService.findByUseridPwd(TipperService.java:22)
How is this caused and how can I solve it?
For reference, here's the full stack trace:
WARNING: EJB5184:A system exception occurred during an invocation on EJB TipperService, method: public com.twibu.entity.Tipper com.twibu.service.TipperService.findByUseridPwd(java.lang.String,java.lang.String)
WARNING: javax.ejb.EJBException
at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5215)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5113)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
at com.sun.proxy.$Proxy141.findByUseridPwd(Unknown Source)
at com.twibu.service.__EJB31_Generated__TipperService__Intf____Bean__.findByUseridPwd(Unknown Source)
at com.twibu.bean.AuthBean.login(AuthBean.java:122)
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 com.sun.el.parser.AstValue.invoke(AstValue.java:254)
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.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: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:722)
Caused by: java.lang.ClassCastException: com.twibu.entity.Tipper cannot be cast to com.twibu.entity.Tipper
at com.twibu.service.TipperService.findByUseridPwd(TipperService.java:22)
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: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:601)
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)
... 44 more
Here's the entity:
#Entity
#Table(name = "tipper")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Tipper.findAll", query = "SELECT t FROM Tipper t"),
#NamedQuery(name = "Tipper.findById", query = "SELECT t FROM Tipper t WHERE t.id = :id"),
#NamedQuery(name = "Tipper.findByName", query = "SELECT t FROM Tipper t WHERE t.name = :name"),
#NamedQuery(name = "Tipper.findByUserid", query = "SELECT t FROM Tipper t WHERE t.userid = :userid"),
#NamedQuery(name = "Tipper.findByPwd", query = "SELECT t FROM Tipper t WHERE t.pwd = :pwd"),
#NamedQuery(name = "Tipper.findByEmail", query = "SELECT t FROM Tipper t WHERE t.email = :email")})
#NamedNativeQueries({
#NamedNativeQuery(name = "Tipper.findByUseridPwd", query = "" +
"SELECT a.id AS id, " +
" a.idgruppe AS idgruppe, " +
" a.name AS name, " +
" a.userid AS userid, " +
" a.pwd AS pwd, " +
" a.email AS email " +
"FROM tipper AS a " +
"WHERE a.userid = ? " +
" AND a.pwd = MD5(?)",
resultClass=Tipper.class)})
public class Tipper implements Serializable {
private static final long serialVersionUID = 20130311L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "userid")
private String userid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 32)
#Column(name = "pwd")
private String pwd;
// #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
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "email")
private String email;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "tipper")
private Collection<Zulassung> zulassungCollection;
#JoinColumn(name = "idgruppe", referencedColumnName = "id")
#ManyToOne(optional = false)
private Gruppe idgruppe;
public Tipper() {
}
public Tipper(Integer id) {
this.id = id;
}
public Tipper(Integer id, String name, String userid, String pwd, String email) {
this.id = id;
this.name = name;
this.userid = userid;
this.pwd = pwd;
this.email = email;
}
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;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#XmlTransient
public Collection<Zulassung> getZulassungCollection() {
return zulassungCollection;
}
public void setZulassungCollection(Collection<Zulassung> zulassungCollection) {
this.zulassungCollection = zulassungCollection;
}
public Gruppe getIdgruppe() {
return idgruppe;
}
public void setIdgruppe(Gruppe idgruppe) {
this.idgruppe = idgruppe;
}
public boolean isUser() {
return idgruppe.getName().equals("user") || idgruppe.getName().equals("admin");
}
public boolean isAdmin() {
return idgruppe.getName().equals("admin");
}
#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 Tipper)) {
return false;
}
Tipper other = (Tipper) 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 "com.twibu.entity.Tipper[ id=" + id + " ]";
}
}
And here's the service class:
#Singleton
public class TipperService extends AbstractService {
public Tipper findByUseridPwd(String userid, String pwd) {
Query nq = getTwibuManager().createNamedQuery("Tipper.findByUseridPwd");
nq.setParameter(1, userid);
nq.setParameter(2, pwd);
return (Tipper)nq.getSingleResult();
}
}
Seems like the old application is not getting undeployed.
If you are not using a container managed persistence unit, then you need to close your EntityManagerFactory when undeploying.
Related
community!
I get an error (Error accessing field) when in application.properties I change the value (spring.jpa.hibernate.ddl-auto) from create-drop to validate or update.
The error occurs when I try to get the OwnerProfile object from the database.
I use:
spring boot: 2.4.1
postgresql driver: 42.2.5
Caused by: org.springframework.orm.jpa.JpaSystemException: Error accessing field [private java.lang.Long giveawaystatistics.model.OwnerProfile.pk] by reflection for persistent property [giveawaystatistics.model.OwnerProfile#pk] : 1; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Long giveawaystatistics.model.OwnerProfile.pk] by reflection for persistent property [giveawaystatistics.model.OwnerProfile#pk] : 1
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:331) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:145) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.2.jar:5.3.2]
at com.sun.proxy.$Proxy98.findOwnerProfileByPk(Unknown Source) ~[na:na]
at com.gmail.andreyzarazka.giveawaystatistics.service.impl.OwnerProfileServiceImpl.info(OwnerProfileServiceImpl.java:50) ~[classes/:na]
at com.gmail.andreyzarazka.giveawaystatistics.GiveawayStatisticsApp.lambda$commandLineRunner$0(GiveawayStatisticsApp.java:44) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:804) ~[spring-boot-2.4.1.jar:2.4.1]
... 10 common frames omitted
Caused by: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Long giveawaystatistics.model.OwnerProfile.pk] by reflection for persistent property [giveawaystatistics.model.OwnerProfile#pk] : 1
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:75) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.tuple.component.AbstractComponentTuplizer.getPropertyValue(AbstractComponentTuplizer.java:59) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.type.ComponentType.getPropertyValue(ComponentType.java:419) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.type.ComponentType.getHashCode(ComponentType.java:246) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.spi.EntityUniqueKey.generateHashCode(EntityUniqueKey.java:67) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.spi.EntityUniqueKey.<init>(EntityUniqueKey.java:48) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:748) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.type.EntityType.resolve(EntityType.java:467) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.internal.TwoPhaseLoad$EntityResolver.lambda$static$0(TwoPhaseLoad.java:605) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntityEntryLoadedState(TwoPhaseLoad.java:248) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:182) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:151) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1200) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.processResultSet(Loader.java:1001) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:959) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2850) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2832) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2664) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.list(Loader.java:2659) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:506) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:400) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:219) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1414) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1625) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1593) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.query.internal.AbstractProducedQuery.getSingleResult(AbstractProducedQuery.java:1641) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:111) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:406) ~[spring-orm-5.3.2.jar:5.3.2]
at com.sun.proxy.$Proxy115.getSingleResult(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:196) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:88) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:155) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:143) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:152) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:131) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.2.jar:5.3.2]
... 20 common frames omitted
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field giveawaystatistics.model.OwnerProfile.pk to java.lang.Long
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36) ~[na:na]
at java.base/java.lang.reflect.Field.get(Field.java:419) ~[na:na]
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:71) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
... 69 common frames omitted
My application.properties file looks like this
spring.datasource.url=jdbc:postgresql://localhost:5432/gsdb
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=true
#Entity(name = "OwnerProfile")
#Table(name = "owner_profile",
uniqueConstraints = {
#UniqueConstraint(
name = "owner_profile_pk_unique",
columnNames = "pk"),
#UniqueConstraint(
name = "owner_profile_username_unique",
columnNames = "username")})
public class OwnerProfile implements Serializable {
#Id
#SequenceGenerator(
name = "owner_profile_sequence",
sequenceName = "owner_profile_sequence",
allocationSize = 1)
#GeneratedValue(
strategy = SEQUENCE,
generator = "owner_profile_sequence")
#Column(
name = "id",
updatable = false)
private Long id;
#Column(
name = "pk",
nullable = false,
updatable = false)
private Long pk;
#Column(
name = "username",
nullable = false,
columnDefinition = "TEXT")
private String username;
#Column(
name = "profile_pic_url",
nullable = false,
columnDefinition = "TEXT")
private String profilePicUrl;
#Column(
name = "phone_number",
nullable = true,
columnDefinition = "TEXT")
private String phoneNumber;
#OneToOne(
mappedBy = "ownerProfile",
cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
private Company company;
public OwnerProfile() {
}
public OwnerProfile(SelfProfile profile) {
this.pk = profile.getPk();
this.username = profile.getUsername();
this.profilePicUrl = profile.getProfilePicUrl();
this.phoneNumber = profile.getPhoneNumber();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPk() {
return pk;
}
public void setPk(Long pk) {
this.pk = pk;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getProfilePicUrl() {
return profilePicUrl;
}
public void setProfilePicUrl(String profilePicUrl) {
this.profilePicUrl = profilePicUrl;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Company)) return false;
Company company = (Company) o;
return getId().equals(company.getId())
&& getPk().equals(company.getPk())
&& getUsername().equals(company.getUsername());
}
#Override
public int hashCode() {
return Objects.hash(getId(), getPk(), getUsername());
}
#Override
public String toString() {
return "OwnerProfileService{" +
"id=" + id +
", pk=" + pk +
", username='" + username + '\'' +
", profilePicUrl='" + profilePicUrl + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
'}';
}
}
#Entity(name = "Company")
#Table(
name = "company",
uniqueConstraints = {
#UniqueConstraint(
name = "company_pk_unique",
columnNames = "pk"),
#UniqueConstraint(
name = "company_username_unique",
columnNames = "username")})
public class Company implements Serializable {
#Id
#SequenceGenerator(
name = "company_sequence",
sequenceName = "company_sequence",
allocationSize = 1)
#GeneratedValue(
strategy = SEQUENCE,
generator = "company_sequence")
#Column(
name = "id",
updatable = false)
private Long id;
#Column(
name = "pk",
nullable = false,
updatable = false)
private Long pk;
#Column(
name = "username",
nullable = false,
columnDefinition = "TEXT")
private String username;
#Column(
name = "full_name",
nullable = true,
columnDefinition = "TEXT")
private String fullName;
#Column(
name = "profile_pic_url",
nullable = false,
columnDefinition = "TEXT")
private String profilePicUrl;
#Column(
name = "profile_pic_id",
nullable = true,
columnDefinition = "TEXT")
private String profilePicId;
#Column(
name = "following_count",
nullable = false)
private Integer followingCount;
#Column(
name = "biography",
nullable = true,
columnDefinition = "TEXT")
private String biography;
#Column(
name = "account_type",
nullable = false)
private Integer accountType;
#Column(
name = "is_private",
nullable = false,
columnDefinition = "boolean default false")
private Boolean isPrivate;
#Column(
name = "is_business",
nullable = false,
columnDefinition = "boolean default false")
private Boolean isBusiness;
#OneToOne(
cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
#JoinColumn(
name = "owner_profile_pk",
referencedColumnName = "pk",
foreignKey = #ForeignKey(
name = "owner_profile_pk_fk"))
private OwnerProfile ownerProfile;
#OneToMany(
mappedBy = "company",
orphanRemoval = true,
cascade = CascadeType.ALL)
private Set<CompanyRegistration> companyRegistrations = new HashSet<>();
#OneToMany(
mappedBy = "company",
orphanRemoval = true,
cascade = CascadeType.ALL)
private Set<GiveawayFollowers> giveawayFollowers = new HashSet<>();
#OneToMany(
mappedBy = "company",
orphanRemoval = true,
cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
private Set<TargetAudience> targetAudiences = new HashSet<>();
public Company() {
}
public Company(User user) {
this.pk = user.getPk();
this.username = user.getUsername();
this.fullName = user.getFull_name();
this.profilePicUrl = user.getProfile_pic_url();
this.profilePicId = user.getProfile_pic_id();
this.followingCount = user.getFollowing_count();
this.biography = user.getBiography();
this.accountType = user.getAccount_type();
this.isPrivate = user.is_private();
this.isBusiness = user.is_business();
}
public Company(Long pk,
String username,
String fullName,
String profilePicUrl,
String profilePicId,
Integer followingCount,
String biography,
Integer accountType,
Boolean isPrivate,
Boolean isBusiness) {
this.pk = pk;
this.username = username;
this.fullName = fullName;
this.profilePicUrl = profilePicUrl;
this.profilePicId = profilePicId;
this.followingCount = followingCount;
this.biography = biography;
this.accountType = accountType;
this.isPrivate = isPrivate;
this.isBusiness = isBusiness;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPk() {
return pk;
}
public void setPk(Long pk) {
this.pk = pk;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getProfilePicUrl() {
return profilePicUrl;
}
public void setProfilePicUrl(String profilePicUrl) {
this.profilePicUrl = profilePicUrl;
}
public String getProfilePicId() {
return profilePicId;
}
public void setProfilePicId(String profilePicId) {
this.profilePicId = profilePicId;
}
public Integer getFollowingCount() {
return followingCount;
}
public void setFollowingCount(Integer followingCount) {
this.followingCount = followingCount;
}
public String getBiography() {
return biography;
}
public void setBiography(String biography) {
this.biography = biography;
}
public Integer getAccountType() {
return accountType;
}
public void setAccountType(Integer accountType) {
this.accountType = accountType;
}
public Boolean getPrivate() {
return isPrivate;
}
public void setPrivate(Boolean aPrivate) {
isPrivate = aPrivate;
}
public Boolean getBusiness() {
return isBusiness;
}
public void setBusiness(Boolean business) {
isBusiness = business;
}
public OwnerProfile getOwnerProfile() {
return ownerProfile;
}
public void setOwnerProfile(OwnerProfile ownerProfile) {
this.ownerProfile = ownerProfile;
}
public Set<CompanyRegistration> getCompanyRegistrations() {
return companyRegistrations;
}
public void addCompanyRegistration(CompanyRegistration companyRegistration) {
companyRegistrations.add(companyRegistration);
}
public void removeCompanyRegistration(CompanyRegistration companyRegistration) {
companyRegistrations.remove(companyRegistration);
}
public Set<GiveawayFollowers> getGiveawayFollowers() {
return giveawayFollowers;
}
public void addGiveawayFollower(GiveawayFollowers giveawayFollowers) {
this.giveawayFollowers.add(giveawayFollowers);
}
public void removeGiveawayFollower(GiveawayFollowers giveawayFollowers) {
this.giveawayFollowers.remove(giveawayFollowers);
}
public Set<TargetAudience> getTargetAudiences() {
return targetAudiences;
}
public void addTargetAudience(TargetAudience targetAudience) {
this.targetAudiences.add(targetAudience);
}
public void removeTargetAudience(TargetAudience targetAudience) {
this.targetAudiences.remove(targetAudience);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Company)) return false;
Company company = (Company) o;
return getId().equals(company.getId())
&& getPk().equals(company.getPk())
&& getUsername().equals(company.getUsername());
}
#Override
public int hashCode() {
return Objects.hash(getId(), getPk(), getUsername());
}
#Override
public String toString() {
return "CompanyDetails{" +
"id=" + id +
", pk=" + pk +
", username='" + username + '\'' +
", fullName='" + fullName + '\'' +
", profilePicUrl='" + profilePicUrl + '\'' +
", profilePicId=" + profilePicId +
", followingCount=" + followingCount +
", biography='" + biography + '\'' +
", accountType=" + accountType +
", isPrivate=" + isPrivate +
", isBusiness=" + isBusiness +
'}';
}
}
public interface OwnerProfileRepository extends JpaRepository<OwnerProfile, Long> {
Optional<OwnerProfile> findOwnerProfileByPk(Long pk);
}
Any idea why this is happening and how you can fix it?
I try executing a dynamic query using ParameterExpression but get an exception.
my method:
public List<Atividade> buscarAtividades(Armario armario) {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<Atividade> criteriaQuery = builder.createQuery(Atividade.class);
Root<Atividade> atividade = criteriaQuery.from(Atividade.class);
criteriaQuery.select(atividade);
criteriaQuery.distinct(true);
List<Predicate> predicates = new ArrayList<Predicate>();
if(armario != null){
ParameterExpression<Armario> ard = builder.parameter(Armario.class, "ard");
predicates.add(builder.equal(atividade.get("armario").get("numero"), ard));
}
criteriaQuery.where(predicates.toArray(new Predicate[0]));
TypedQuery<Atividade> query = manager.createQuery(criteriaQuery);
return query.getResultList();
}
When my query is executed I receive stack:
fev 02, 2017 11:31:49 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
ADVERTÊNCIA: #{cadastroAtividadeBean.buscarAtividades}: org.hibernate.QueryException: Named parameter [ard] not set
javax.faces.FacesException: #{cadastroAtividadeBean.buscarAtividades}: org.hibernate.QueryException: Named parameter [ard] not set
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
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:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:509)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.faces.el.EvaluationException: org.hibernate.QueryException: Named parameter [ard] not set
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 28 more
Caused by: org.hibernate.QueryException: Named parameter [ard] not set
at org.hibernate.query.internal.QueryParameterBindingsImpl.verifyParametersBound(QueryParameterBindingsImpl.java:234)
at org.hibernate.query.internal.AbstractProducedQuery.beforeQuery(AbstractProducedQuery.java:1307)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1396)
at org.hibernate.Query.getResultList(Query.java:417)
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:72)
at com.vivo.tecnico.repository.AtividadesRepository.buscarAtividades(AtividadesRepository.java:49)
at com.vivo.tecnico.controller.CadastroAtividadeBean.buscarAtividades(CadastroAtividadeBean.java:85)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 29 more
fev 02, 2017 11:31:49 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
GRAVE: javax.faces.el.EvaluationException: org.hibernate.QueryException: Named parameter [ard] not set
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
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:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
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:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:509)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.QueryException: Named parameter [ard] not set
at org.hibernate.query.internal.QueryParameterBindingsImpl.verifyParametersBound(QueryParameterBindingsImpl.java:234)
at org.hibernate.query.internal.AbstractProducedQuery.beforeQuery(AbstractProducedQuery.java:1307)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1396)
at org.hibernate.Query.getResultList(Query.java:417)
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:72)
at com.vivo.tecnico.repository.AtividadesRepository.buscarAtividades(AtividadesRepository.java:49)
at com.vivo.tecnico.controller.CadastroAtividadeBean.buscarAtividades(CadastroAtividadeBean.java:85)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 29 more
Any idea where is might be a problem ?
I looking for many post about but always stack.
Armario.class
package com.vivo.tecnico.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Armario {
private Long id;
private String numero;
private String endereco;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Armario other = (Armario) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
Atividade.class
package com.vivo.tecnico.model;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
public class Atividade {
private Long id;
private String numero;
private String cidade;
private Armario armario;
private Date dataAtividade;
private Date dataEncerramento;
private String endereco;
private Funcionario funcionario;
private Causa causa;
private Segmento segmento;
private Status status;
private String observacao;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "armario")
public Armario getArmario() {
return armario;
}
public void setArmario(Armario armario) {
this.armario = armario;
}
#Temporal(TemporalType.DATE)
#Column(name = "data_atividade")
public Date getDataAtividade() {
return dataAtividade;
}
public void setDataAtividade(Date dataAtividade) {
this.dataAtividade = dataAtividade;
}
#Temporal(TemporalType.DATE)
#Column(name = "data_encerramento")
public Date getDataEncerramento() {
return dataEncerramento;
}
public void setDataEncerramento(Date dataEncerramento) {
this.dataEncerramento = dataEncerramento;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "funcionario_id")
public Funcionario getFuncionario() {
return funcionario;
}
public void setFuncionario(Funcionario funcionario) {
this.funcionario = funcionario;
}
#Enumerated(EnumType.STRING)
public Causa getCausa() {
return causa;
}
public void setCausa(Causa causa) {
this.causa = causa;
}
#Enumerated(EnumType.STRING)
public Segmento getSegmento() {
return segmento;
}
public void setSegmento(Segmento segmento) {
this.segmento = segmento;
}
#Enumerated(EnumType.STRING)
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getObservacao() {
return observacao;
}
public void setObservacao(String observacao) {
this.observacao = observacao;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Atividade other = (Atividade) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
When you define a parameter in a Criteria query (builder.parameter(Armario.class, "ard") which creates a parameter with name ard) you then need to set the value of the parameter to use when running it.
In your case this means
query.setParameter("ard", someValue);
before calling query.getResultList().
you can use ParameterExpression like this:
assume that you have some input filter, an example could be this:
in your query you have to check the value of a fiscal Code.
1) inizialize a predicateList(use for where clause) and a paramList(use for param)
Map<ParameterExpression,String> paramList = new HashMap();
List<Predicate> predicateList = new ArrayList<>();
2 )check if the input is null and create predicateList and param
if( input.getFilterCF() != null){
//create ParameterExpression
ParameterExpression<String> cf = cb.parameter(String.class);
//if like clause
predicateList.add(cb.like(root.<String>get("cf"), cf));
paramList.put(cf , input.getFilterCF() + "%");
//if equals clause
//predicateList.add(cb.equal(root.get("cf"), cf));
//paramList.put(cf,input.getFilterCF()());
}
3) create the where clause
cq.where(cb.and(predicateList.toArray(new Predicate[predicateList.size()])));
TypedQuery<Tuple> q = _em.createQuery(cq);
4) set param value
for(Map.Entry<ParameterExpression,String> entry : paramList.entrySet())
{
q.setParameter(entry.getKey(), entry.getValue());
}
You have to join the associated entity to access its fields for operation like adding filter or cascading the joins. Also if you are adding a parameter to query, set the parameter before executing it.
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<Atividade> criteriaQuery = builder.createQuery(c.class);
Root<Atividade> atividade = criteriaQuery.from(Atividade.class);
criteriaQuery.select(atividade);
criteriaQuery.distinct(true);
Join<Atividade, Armario> armarioJoin = atividade.join("armario", JoinType.INNER)
List<Predicate> predicates = new ArrayList<Predicate>();
if(armario != null){
ParameterExpression<Armario> ard = builder.parameter(String.class, "ard");
predicates.add(builder.equal(armarioJoin.get("numero"), ard));
}
criteriaQuery.where(predicates.toArray(new Predicate[0]));
TypedQuery<Atividade> query = manager.createQuery(criteriaQuery);
query.setParameter("ard", armario.getNumero());
return query.getResultList()
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
MY Entity class
#Entity
#Table(catalog = "", schema = "MYIS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Answers.findAll", query = "SELECT a FROM Answers a"),
#NamedQuery(name = "Answers.findByAid", query = "SELECT a FROM Answers a WHERE a.aid = :aid"),
#NamedQuery(name ="Anaswers.findByqid", query ="SELECT a FROM Answers a WHERE a.answerQid.qid = :x"),
#NamedQuery(name = "Answers.findByAnsValue", query = "SELECT a FROM Answers a WHERE a.ansValue = :ansValue"),
#NamedQuery(name = "Answers.findByAnsDate", query = "SELECT a FROM Answers a WHERE a.ansDate = :ansDate")})
public class Answers implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(nullable = false)
private Integer aid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 4000)
#Column(name = "ANS_VALUE", nullable = false, length = 4000)
private String ansValue;
#Basic(optional = false)
#NotNull
#Column(name = "ANS_DATE", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
private Date ansDate;
#JoinColumn(name = "A_USERID", referencedColumnName = "USERID", nullable = false)
#ManyToOne(optional = false)
private Users aUserid;
#JoinColumn(name = "ANSWER_QID", referencedColumnName = "QID", nullable = false)
#ManyToOne(optional = false)
private Questions answerQid;
#JoinColumn(name = "A_GROUPID", referencedColumnName = "GID", nullable = false)
#ManyToOne(optional = false)
private Groups aGroupid;
public Answers() {
}
public Answers(Integer aid) {
this.aid = aid;
}
public Answers(Integer aid, String ansValue, Date ansDate) {
this.aid = aid;
this.ansValue = ansValue;
this.ansDate = ansDate;
}
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public String getAnsValue() {
return ansValue;
}
public void setAnsValue(String ansValue) {
this.ansValue = ansValue;
}
public Date getAnsDate() {
return ansDate;
}
public void setAnsDate(Date ansDate) {
this.ansDate = ansDate;
}
public Users getAUserid() {
return aUserid;
}
public void setAUserid(Users aUserid) {
this.aUserid = aUserid;
}
public Questions getAnswerQid() {
return answerQid;
}
public void setAnswerQid(Questions answerQid) {
this.answerQid = answerQid;
}
public Groups getAGroupid() {
return aGroupid;
}
public void setAGroupid(Groups aGroupid) {
this.aGroupid = aGroupid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (aid != null ? aid.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 Answers)) {
return false;
}
Answers other = (Answers) object;
if ((this.aid == null && other.aid != null) || (this.aid != null && !this.aid.equals(other.aid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Answers[ aid=" + aid + " ]";
}
}
MY SESSION FACADE
import com.entity.Answers;
import com.entity.Groups;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* #author krishna teja
*/
#Stateless
public class AnswersFacade extends AbstractFacade<Answers> implements AnswersFacadeLocal {
#PersistenceContext(unitName = "My_communityPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public AnswersFacade() {
super(Answers.class);
}
public List<Answers> getdataByQid(Long qid){
Query query=em.createNamedQuery("Answers.findByqid");
query.setParameter(1, qid);
List<Answers> a =query.getResultList();
return a;
}
}
My managed bean
#PostConstruct
public void init(){
questions = questionsFacade.findAll();
ansList = answersFacade.getdataByQid(g);
}
I am getting following exception
at com.ejb.AnswersFacade.getdataByQid(AnswersFacade.java:36)
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)
I have created named query for the foreign key attribute answerQid and and created method in the sessionfacade and tried to access it in the managed bean the default methods work perfectly but my method for query is not working please help me
Looks like a simple typo. Named query is defined as Anaswers.findByqid, but used as Answers.findByqid.
sorry for my bad english and may be bad question. I have this:
Entity
#Entity
#Table(name = "Books")
#NamedQueries({
#NamedQuery(name = "BooksEntity.findAll", query = "SELECT u FROM BooksEntity u"),
#NamedQuery(name = "BooksEntity.findByBookId", query = "SELECT u FROM BooksEntity u WHERE u.book_id = :book_id"),
#NamedQuery(name = "BooksEntity.findByTitle", query = "SELECT u FROM BooksEntity u WHERE u.title = :title")})
public class BooksEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "book_id",unique=true, nullable=false)
#GeneratedValue(strategy = GenerationType.TABLE)
private Long book_id;
#ManyToOne
#JoinColumn(name = "author", nullable=true)
private AuthorsEntity author;
#OneToMany (mappedBy="book")
private List<UsersEntity> users;
//set and get
}
#Entity
#Table(name = "Users")
#NamedQueries({
#NamedQuery(name = "UsersEntity.findAll", query = "SELECT u FROM UsersEntity u"),
#NamedQuery(name = "UsersEntity.findByUserId", query = "SELECT u FROM UsersEntity u WHERE u.user_id = :user_id"),
#NamedQuery(name = "UsersEntity.findByUserIdAndPassword", query = "SELECT u FROM UsersEntity u WHERE u.user_id = :user_id AND u.password = :password"),
#NamedQuery(name = "UsersEntity.findByName", query = "SELECT u FROM UsersEntity u WHERE u.name = :name"),
#NamedQuery(name = "UsersEntity.findByNameAndPassword", query = "SELECT u FROM UsersEntity u WHERE u.name = :name AND u.password = :password"),
#NamedQuery(name = "UsersEntity.findByEmail", query = "SELECT u FROM UsersEntity u WHERE u.email = :email")})
public class UsersEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "user_id", unique=true, nullable=false)
#GeneratedValue(strategy = GenerationType.TABLE)
private Long user_id;
#Column(name = "name", nullable = false, unique = true)
private String name;
#ManyToOne
#JoinColumn(name = "book")
private BooksEntity book;
}
And manager
#Stateless
public class BookManager implements BookManagerLocal {
#PersistenceContext
EntityManager em;
#EJB
UserManagerLocal um;
#Override
public List<BooksEntity> getAllBooks() {
List<BooksEntity> books = em.createNamedQuery("BooksEntity.findAll").getResultList();
if (!books.isEmpty()) {
return books;
} else {
return null;
}
}
#Override
public List<BooksEntity> getAllBooksUser(String name) {
List<UsersEntity> users;
List<BooksEntity> books = this.getAllBooks();
if (books.isEmpty()) {
return null;
} else {
List<BooksEntity> userbooks = new ArrayList<BooksEntity>();
for (BooksEntity book : books) {
users = book.getUsers();
for (UsersEntity user : users) {
if (name.equals(user.getName())) {
userbooks.add(book);
}
}
}
if (!userbooks.isEmpty()) {
return userbooks;
} else {
return null;
}
}
}
}
I need have all books for one user. But i have problem with it. I do
so
#Override
public List<BooksEntity> getAllBooks() {
List<BooksEntity> books = em.createNamedQuery("BooksEntity.findAll").getResultList();
if (!books.isEmpty()) {
return books;
} else {
return null;
}
}
#Override
public List<BooksEntity> getAllBooksUser(String name) {
List<UsersEntity> users;
List<BooksEntity> books = this.getAllBooks();
if (books.isEmpty()) {
return null;
} else {
List<BooksEntity> userbooks = new ArrayList<BooksEntity>();
for (BooksEntity book : books) {
users = book.getUsers();
for (UsersEntity user : users) {
if (name.equals(user.getName())) {
userbooks.add(book);
}
}
}
if (!userbooks.isEmpty()) {
return userbooks;
} else {
return null;
}
}
}
But it does not work. i have ejbexception and nullpointexception.
WARNING: EJB5184:A system exception occurred during an invocation on EJB BookManager, method: public java.util.List book.ejb.BookManager.getAllBooksUser(java.lang.String)
WARNING: javax.ejb.EJBException
at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5215)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5113)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
at $Proxy230.getAllBooksUser(Unknown Source)
at book.bean.BookEditBean.getUserBooks(BookEditBean.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:363)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstValue.getValue(AstValue.java:138)
at com.sun.el.parser.AstValue.getValue(AstValue.java:183)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:224)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at com.sun.faces.facelets.component.UIRepeat.getValue(UIRepeat.java:273)
at com.sun.faces.facelets.component.UIRepeat.getDataModel(UIRepeat.java:249)
at com.sun.faces.facelets.component.UIRepeat.setIndex(UIRepeat.java:443)
at com.sun.faces.facelets.component.UIRepeat.process(UIRepeat.java:482)
at com.sun.faces.facelets.component.UIRepeat.encodeChildren(UIRepeat.java:984)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1757)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1757)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1757)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
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: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:722)
Caused by: java.lang.NullPointerException
at book.ejb.BookManager.getAllBooksUser(BookManager.java:87)
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: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 org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:42)
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 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.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:601)
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)
... 61 more
Can you help me? Thanks for all you.
You're using a bad practice, and by using it, you're directly affected. A method returning a List (or any kind of collection), should never return null. It should return an empty list if there's nothing to return. By returning null, you force every caller, including yourself, to always check for null before using the returned list, which you failed to do:
List<BooksEntity> books = this.getAllBooks();
if (books.isEmpty()) {
return null;
}
In the above code, you don't check if books is null before calling isEmpty(). And since getAllBooks() returns null instead of an empty list in case no book is found, you get a NullPointerException.
Here's how I would rewrite your code:
#Override
public List<BooksEntity> getAllBooks() {
return em.createNamedQuery("BooksEntity.findAll").getResultList();
}
#Override
public List<BooksEntity> getAllBooksUser(String name) {
List<BooksEntity> books = this.getAllBooks();
List<BooksEntity> userbooks = new ArrayList<BooksEntity>();
for (BooksEntity book : books) {
users = book.getUsers();
for (UsersEntity user : users) {
if (name.equals(user.getName())) {
userbooks.add(book);
}
}
}
return userBooks;
}
Note how the code is much shorter, and how it doesn't have a risk of throwing a NullPointerException.
That said, your method of finding the books for a given user name is extremely inefficient: you're loading every book (imagine doing that with a real library), and for every book, you're loading all its users.
It would be much more efficient to find all the users with the given name (using the findByName named query, for example), and return their book. Or even better, to do all this in a single JPQL query:
select book from UsersEntity user
inner join user.book book
where user.name = :name
The method would then look like this:
public List<BooksEntity> getAllBooksUser(String name) {
String jpql =
"select book from UsersEntity user"
+ " inner join user.book book"
+ " where user.name = :name";
return em.createTypedQuery(jpql, BooksEntity.class)
.setParameter("name", name)
.getResultList();
}
Finally, your code would be more readable if you named your entities Book and User, instead of BooksEntity and UsersEntity. Using the plural form for a single user or book is a really bad idea. And the Entity suffix is annoying noise.