java.lang.ClassCastException: java.util.HashMap cannot be cast to ClassObject - spring

I have a problem with <p:dataTable> in PrimeFaces, I can not find the error.
Class UsuarioAsig:
public class UsuarioAsig {
private BigDecimal codigopersona;
private String nombre;
private String paterno;
private String materno;
private String login;
private String observacion;
private String tipocontrol;
private String externo;
private String habilitado;
private String nombreperfil;
private BigDecimal codigousuario; ...get and set...}
Class UsuarioAsigListaDataModel:
public class UsuarioAsigListaDataModel extends ListDataModel<UsuarioAsig> implements SelectableDataModel<UsuarioAsig> {
public UsuarioAsigListaDataModel(){}
public UsuarioAsigListaDataModel(List<UsuarioAsig> data){super(data);}
#Override
public UsuarioAsig getRowData(String rowKey) {
#SuppressWarnings("unchecked")
List<UsuarioAsig> listaUsuarioAsigLectura = (List<UsuarioAsig>) getWrappedData();
for (UsuarioAsig usuarioAsig : listaUsuarioAsigLectura) {
if (usuarioAsig.getCodigopersona().equals(rowKey)) { return usuarioAsig; }
}
return null;
}
#Override
public Object getRowKey(UsuarioAsig usuarioAsig) {
return usuarioAsig.getCodigopersona();
}}
Controller UsuarioAsigController:
#Controller("usuarioAsigController")
#Scope(value = "session")
public class UsuarioAsigController {
private List<UsuarioAsig> listaUsuarioAsig;
private HashMap<String, Object> selUsuarioAsig;
private UsuarioAsigListaDataModel mediumUsuarioAsigModel;
#Autowired
UsuarioService usuarioService;
...
public List<UsuarioAsig> getListaUsuarioAsig() {
listaUsuarioAsig = usuarioService.selectAsig();
return listaUsuarioAsig;
}
public void setListaUsuarioAsig(List<UsuarioAsig> listaUsuarioAsig) {
this.listaUsuarioAsig = listaUsuarioAsig;
}
public void setMediumUsuarioAsigModel(UsuarioAsigListaDataModel mediumUsuarioAsigModel) {
this.mediumUsuarioAsigModel = mediumUsuarioAsigModel;
}
public UsuarioAsigListaDataModel getMediumUsuarioAsigModel() {
listaUsuarioAsig = usuarioService.selectAsig();
mediumUsuarioAsigModel = new UsuarioAsigListaDataModel(listaUsuarioAsig);
return mediumUsuarioAsigModel;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("Usuario seleccionado", ((UsuarioAsig) event.getObject()).getNombre());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
the error is generated when you click on one of the lines of datatable:
asiginst.xhtml:
<h:form id="form">
<p:growl id="msgs" showDetail="true" />
<p:dataTable id="usuarioAsigListaDataModel" var="usuarioAsig"
value="#{usuarioAsigController.mediumUsuarioAsigModel}"
rowKey="#{usuarioAsig.codigopersona}"
selection="#{usuarioAsigController.selUsuarioAsig}"
selectionMode="single" paginator="true" rows="10">
<p:ajax event="rowSelect"
listener="#{usuarioAsigController.onRowSelect}"
update=":form:msgs" />
<p:column headerText="Código" style="width:10%">#{usuarioAsig.codigopersona}</p:column>
<p:column headerText="Nombre" style="width:32%">#{usuarioAsig.nombre}</p:column>
<p:column headerText="Apellidos" style="width:32%">#{usuarioAsig.paterno} #{usuarioasig.materno}</p:column>
<p:column headerText="Tipo Control" style="width:20%">#{usuarioAsig.tipocontrol}</p:column>
<p:column headerText="Habilitado" style="width:6%">#{usuarioAsig.habilitado}</p:column>
</p:dataTable>
</h:form>
THE ERROR IS GENERATED:
WARNING: asiginst.xhtml #51,103 listener="#{usuarioAsigController.onRowSelect}": java.lang.ClassCastException: java.util.HashMap cannot be cast to com.datos.entidades.qry.UsuarioAsig
javax.el.ELException: asiginst.xhtml #51,103 listener="#{usuarioAsigController.onRowSelect}": java.lang.ClassCastException: java.util.HashMap cannot be cast to com.datos.entidades.qry.UsuarioAsig
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
at org.primefaces.behavior.ajax.AjaxBehaviorListenerImpl.processArgListener(AjaxBehaviorListenerImpl.java:69)
at org.primefaces.behavior.ajax.AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxBehaviorListenerImpl.java:56)
at org.primefaces.event.SelectEvent.processListener(SelectEvent.java:40)
at javax.faces.component.behavior.BehaviorBase.broadcast(BehaviorBase.java:102)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:760)
at javax.faces.component.UIData.broadcast(UIData.java:1071)
at javax.faces.component.UIData.broadcast(UIData.java:1093)
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:409)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to com.datos.entidades.qry.UsuarioAsig
at com.controller.UsuarioAsigController.onRowSelect(UsuarioAsigController.java:217)
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.apache.el.parser.AstValue.invoke(AstValue.java:264)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
... 29 more

I'm assuming that the HashMap<String, Object> selUsuarioAsig is your selection.
Then in the method
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("Usuario seleccionado", ((UsuarioAsig) event.getObject()).getNombre());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
You are attempting to cast the HashMap to a UsuarioAsig: ((UsuarioAsig) event.getObject())

as examples of http://www.primefaces.org/showcase/ui/data/datatable/selection.xhtml, not generate error in other tables, after much testing error was mybatis mapper, since the resulMap was in type Map.

Related

Update Password Using Spring Boot and JPA Is Not Working

I am developing a web application in which there is a feature to generate the password. I am using Spring Boot + Hibernate + JPA. I am able to use built-in JPA query like findByUserMobileNumber etc. But when it is coming to update the password in the database I am getting the error.
Here is my entity class:
package gvr.OtpOnWeb.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="tbl_users")
public class Users
{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PK_AI_unbUserID")
private int userID;
#Column(name= "svName")
private String userName;
#Column(name = "UQ_svMobileNo")
private String userMobileNumber;
#Column(name="svEmailID")
private String userEmailId;
#Column(name= "bActiveFlag")
private int active;
#Column(name="svPassword")
private String password;
public Users()
{
super();
}
public Users(int userID, String userName, String userMobileNumber, String userEmailId, int active,
String password)
{
super();
this.userID = userID;
this.userName = userName;
this.userMobileNumber = userMobileNumber;
this.userEmailId = userEmailId;
this.active = active;
this.password = password;
}
public Users(Users users)
{
this.active = users.getActive();
this.userEmailId = users.getUserEmailId();
this.userName = users.getUserName();
this.userMobileNumber = users.getUserMobileNumber();
this.password = users.getPassword();
}
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserMobileNumber() {
return userMobileNumber;
}
public void setUserMobileNumber(String userMobileNumber) {
this.userMobileNumber = userMobileNumber;
}
public String getUserEmailId() {
return userEmailId;
}
public void setUserEmailId(String userEmailId) {
this.userEmailId = userEmailId;
}
public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Here is repository code:
#Repository
public interface UserRepository extends JpaRepository<Users, Integer>, CrudRepository<Users, Integer> {
Users findByuserMobileNumber(String mobileNumber);
Users findByuserMobileNumberAndPassword(String mobileNumber, String password);
#Modifying
#Query("update tbl_users u set u.svPassword = :password where u.UQ_svMobileNo = :mobilenumber")
void updateuserPassword(#Param("password") String password, #Param("mobilenumber") String mobilenumber);
}
Here is my controller code:
#RequestMapping(value = "GeneratePassword", method = RequestMethod.POST)
public ModelAndView generatePassword(#ModelAttribute(name="generatePasswordForm") Password passwordObj, Model model)
{
String mobileNumber = passwordObj.getMobileNumber();
String enteredPassword = passwordObj.getPassword();
String confirmPassword = passwordObj.getConfirmPassword();
ModelAndView modelAndView = new ModelAndView("GeneratePassword");
logger.info("Entered Mobile Number :"+ mobileNumber);
logger.info("Entered Password :"+ enteredPassword);
logger.info("Entered Confirmed Password :"+ confirmPassword);
userObj = userRepository.findByuserMobileNumber(mobileNumber);
if(userObj == null)
{
logger.info("USER DOES NOT EXIST");
modelAndView.addObject("messageFromServer", "Mobile Number Is Not Registered");
}
else
{
logger.info("VALIDATING PASSWORD");
boolean isEnteredPasswordValid = validationObj.validatePassword(enteredPassword);
logger.info("IS PASSWORD VALID :"+ isEnteredPasswordValid);
boolean isConfirmPasswordValid = validationObj.validatePassword(confirmPassword);
logger.info("IS CONFIRMED PASSWORD VALID :"+ isConfirmPasswordValid);
boolean arePasswordSame = validationObj.arePasswordSame(enteredPassword, confirmPassword);
logger.info("ARE BOTH THE PASSWORD SAME :"+ arePasswordSame);
if(isEnteredPasswordValid == false)
{
String messageToSend = "ENTER PASSWORD IN CORRECT FORMAT";
modelAndView.addObject("messageFromServer", messageToSend);
modelAndView.addObject("mobileNumber", mobileNumber);
return modelAndView;
}
if(isConfirmPasswordValid == false)
{
String messageToSend = "ENTER CONFIRM PASSWORD IN CORRECT FORMAT";
modelAndView.addObject("messageFromServer", messageToSend);
}
if(arePasswordSame == false)
{
String messageToSend = "PASSWORD MISMATCH ERROR";
modelAndView.addObject("messageFromServer", messageToSend);
modelAndView.addObject("mobileNumber", mobileNumber);
}
else
{
// DO FURTHE PROCESSING
// ENCRYPT PASSWORD
String md5ConfirmedPassword = PasswordHashing.cryptWithMD5(confirmPassword);
userRepository.updateuserPassword(md5ConfirmedPassword, mobileNumber);
}
}
return modelAndView;
}
Whenever I start my application I get the following list of errors:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mainController' defined in file [D:\Development\Eclipse Worspaces\otp_on_web\OtpOnWeb\target\classes\gvr\OtpOnWeb\controller\MainController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract void gvr.OtpOnWeb.repository.UserRepository.updateuserPassword(java.lang.String,java.lang.String)!
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:732)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1267)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1124)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:398)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:330)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1258)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246)
at gvr.OtpOnWeb.OtpOnWebApplication.main(OtpOnWebApplication.java:12)
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.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract void gvr.OtpOnWeb.repository.UserRepository.updateuserPassword(java.lang.String,java.lang.String)!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1699)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:573)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:818)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:724)
... 24 more
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract void gvr.OtpOnWeb.repository.UserRepository.updateuserPassword(java.lang.String,java.lang.String)!
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:93)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:63)
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:76)
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:56)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:139)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:206)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:79)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lookupQuery(RepositoryFactorySupport.java:553)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(RepositoryFactorySupport.java:546)
at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
at java.util.Iterator.forEachRemaining(Unknown Source)
at java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Unknown Source)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.collect(Unknown Source)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.mapMethodsToQuery(RepositoryFactorySupport.java:548)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$new$0(RepositoryFactorySupport.java:538)
at java.util.Optional.map(Unknown Source)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:538)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:317)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$3(RepositoryFactoryBeanSupport.java:286)
at org.springframework.data.util.Lazy.getNullable(Lazy.java:141)
at org.springframework.data.util.Lazy.get(Lazy.java:63)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:289)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:102)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1758)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1695)
... 35 more
Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: tbl_users is not mapped [update tbl_users u set u.svPassword = :password where u.UQ_svMobileNo = :mobilenumber]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:133)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:670)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
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.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350)
at com.sun.proxy.$Proxy100.createQuery(Unknown Source)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:87)
... 64 more
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: tbl_users is not mapped [update tbl_users u set u.svPassword = :password where u.UQ_svMobileNo = :mobilenumber]
at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:217)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:553)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:662)
... 72 more
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: tbl_users is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:169)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:326)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3706)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3595)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.updateStatement(HqlSqlBaseWalker.java:377)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:269)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
... 78 more
What could be the probable error for this?
It should be like this :
#Query("update Users u set u.password = :password where u.userMobileNumber = :mobilenumber")

Thymeleaf unexpected and strange class cast exception in view

UPDATE:
EDIT #2 below shows the temporary resolution of this issue, but raises a new question.
I am developing a client using Spring MVC and Thymeleaf for my view.
I have two users, a basic user and an administrator. When a basic user logs in, his personal information is displayed on his home page. When an administrator logs in, he can perform various search operations to find users in a backend database (MongoDB). He can find by state, city, username, etc....
I get this error: java.lang.ClassCastException: formBeans.User cannot be cast to java.util.Map only after I execute a specific sequence of operations on the client:
log in as administrator
search for all users
log out
log back in as basic user
Above error is thrown
Like I said, when a basic user logs in, his personal info is supposed to be displayed. Logging in as a basic user works other times, but not in this specific case. However, this error might occur in other situations that I might not have run into.
Here is my User model and form backing bean class:
package formBeans;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class User {
private String firstname;
private String lastname;
private String username;
private String password;
private String phoneNumber;
private String email;
private String address;
private String city;
private String state;
private String zipCode;
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getEmail() {
return email;
}
public String getAddress() {
return address;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public String getZipCode() {
return zipCode;
}
public void setFirstname(String firstname) {
this.firstname = format(firstname);
}
public void setLastname(String lastname) {
this.lastname = format(lastname);
}
public void setUsername(String username) {
this.username = format(username);
}
public void setPassword(String password) {
this.password = password;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setEmail(String email) {
this.email = format(email);
}
public void setAddress(String address) {
this.address = format(address);
}
public void setCity(String city) {
this.city = format(city);
}
public void setState(String state) {
this.state = format(state);
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String format(String data) {
String firstLetter = data.substring(0, 1).toUpperCase();
String restLetters = data.substring(1).toLowerCase();
return firstLetter + restLetters;
}
}
Here is the basic user's home page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Home</title>
<link rel="stylesheet" th:href="#{/css/topcoat-desktop-light.min.css}" href="../../css/topcoat-desktop-light.min.css"/>
</head>
<body>
<div th:include="fragment :: header"></div>
<h1>Welcome, <span th:text="${credentials.username}"></span> </h1>
<h2>My profile:</h2>
<a th:href="#{/edit}">Edit my profile</a>
<br></br>
<br></br>
<table>
<tr><td>Firstname:</td> <td th:text="${user.firstname}"></td></tr>
<tr><td>Lastname:</td> <td th:text="${user.lastname}"></td></tr>
<tr><td>Username:</td> <td th:text="${user.username}"></td></tr>
<tr><td>Address:</td> <td th:text="${user.address}"></td></tr>
<tr><td>City:</td> <td th:text="${user.city}"></td></tr>
<tr><td>State:</td> <td th:text="${user.state}"></td></tr>
<tr><td>Zip code:</td> <td th:text="${user.zipCode}"></td></tr>
<tr><td>Email:</td> <td th:text="${user.email}"></td></tr>
<tr><td>Phone number:</td> <td th:text="${user.phoneNumber}"></td></tr>
<tr><td><hr></hr></td></tr>
</table>
</body>
</html>
So as you see in the html page, sometimes Thymeleaf cannot recognize the "user" object.
Any ideas?
EDIT: Thanks for the responses. Here is some more relevant code:
Stack trace: The stack trace does not give any error on a particular line number in my view or any of my Java classes. It seems like it is an internal error in the Spring's Java docs.
java.lang.ClassCastException: formBeans.User cannot be cast to java.util.Map
at org.springframework.context.expression.MapAccessor.read(MapAccessor.java:49)
at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:188)
at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:94)
at org.springframework.expression.spel.ast.PropertyOrFieldReference.access$000(PropertyOrFieldReference.java:46)
at org.springframework.expression.spel.ast.PropertyOrFieldReference$AccessorLValue.getValue(PropertyOrFieldReference.java:375)
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:88)
at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:120)
at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:267)
at org.thymeleaf.spring4.expression.SpelVariableExpressionEvaluator.evaluate(SpelVariableExpressionEvaluator.java:139)
at org.thymeleaf.standard.expression.VariableExpression.executeVariable(VariableExpression.java:154)
at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:59)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:103)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:133)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:120)
at org.thymeleaf.standard.processor.attr.AbstractStandardTextChildModifierAttrProcessor.getText(AbstractStandardTextChildModifierAttrProcessor.java:68)
at org.thymeleaf.processor.attr.AbstractTextChildModifierAttrProcessor.getModifiedChildren(AbstractTextChildModifierAttrProcessor.java:59)
at org.thymeleaf.processor.attr.AbstractChildrenModifierAttrProcessor.processAttribute(AbstractChildrenModifierAttrProcessor.java:59)
at org.thymeleaf.processor.attr.AbstractAttrProcessor.doProcess(AbstractAttrProcessor.java:87)
at org.thymeleaf.processor.AbstractProcessor.process(AbstractProcessor.java:212)
at org.thymeleaf.dom.Node.applyNextProcessor(Node.java:1017)
at org.thymeleaf.dom.Node.processNode(Node.java:972)
at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:695)
at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:668)
at org.thymeleaf.dom.Node.processNode(Node.java:990)
at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:695)
at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:668)
at org.thymeleaf.dom.Node.processNode(Node.java:990)
at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:695)
at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:668)
at org.thymeleaf.dom.Node.processNode(Node.java:990)
at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:695)
at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:668)
at org.thymeleaf.dom.Node.processNode(Node.java:990)
at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:695)
at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:668)
at org.thymeleaf.dom.Node.processNode(Node.java:990)
at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:695)
at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:668)
at org.thymeleaf.dom.Node.processNode(Node.java:990)
at org.thymeleaf.dom.Document.process(Document.java:93)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1155)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335)
at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1244)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1027)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
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:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
The "user" object is stored as a session object. Here is some relevant code from the controller:
/* Here are my session attributes */
#Controller
#SessionAttributes({ "credentials", "user" })
public class ViewController implements ErrorController {
/* Here is the login function. If the user is a basic user, it redirects him to /getBasicUser.*/
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(#ModelAttribute("credentials") Credentials credentials,
RedirectAttributes redirect) {
RestTemplate restTemplate = new RestTemplate();
RoleInfo roleInfo = restTemplate.postForObject(
"http://localhost:8080/users/login", credentials,
RoleInfo.class);
if (roleInfo != null) {
if (roleInfo.isAdmin()) {
return "redirect:/adminHome";
} else {
redirect.addFlashAttribute("credentials", credentials);
return "redirect:/getBasicUser";
}
} else {
return "login_fail";
}
}
/* This function GETs the basic user from the back-end (MongoDB) repository and stores it as a session object in the model using redirect.addFlashAttribute("user", user);*/
#RequestMapping(value = "/getBasicUser", method = RequestMethod.GET)
public <T> String getBasicUser(
#ModelAttribute("credentials") Credentials credentials,
Model model, RedirectAttributes redirect) {
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/users/getBasicUser?username="
+ credentials.getUsername();
ResponseEntity<User> responseEntity = restTemplate.exchange(
url,
HttpMethod.GET,
new HttpEntity<T>(createHeaders(credentials.getUsername(),
credentials.getPassword())), User.class);
User user;
user = responseEntity.getBody();
if (user != null) {
redirect.addFlashAttribute("user", user);
System.out.println("username: " + user.getUsername());
return "redirect:/basicHome";
} else {
return "register_fail";
}
}
/* This is the method that returns the home page. If you look at the getBasicUser() method above, it redirects it to this home page */
#RequestMapping(value = "/basicHome", method = RequestMethod.GET)
public String getBasicHomePage() {
return "basic_home";
}
EDIT #2: As per https://github.com/thymeleaf/thymeleaf/issues/357, when I add ${user['firstname']}, ${user['lastname']}, ....etc instead of ${user.firstname}, ${user.lastname}, ...etc to my basicHome.html page, this issue no longer persists.
The original way I implemented this was using Thymeleaf Expression Language whereas the new, resolved way is Spring Expression Language. It seems like Spring stores an object's key-value pairs as a map, and that this new way directly accesses the map's key-value pairs. So accessing user['firstname'], would be equal to "Bob".
But now the question remains, why can it not cast the User object into map, so that I can just access the values using ${user.key}?
I just ran into this same thing when updating from thymeleaf 2 to 3. The issue turned out to be that we had some code that used "field notation" for non-field uses.
For example, we had:
th:if="*{someProperty}"
Instead of:
th:if="${bean.someProperty}"
I had to just make this simple fix to a couple forms and we were good to go.

How to get Dynamic Drop Down Box in JSP

I want to populate a dropdown box in Spring MVC i tried to do this but i am getting null pointer exception
this is my controller:
public class CatalogueController {
private CatalogueService catalogueService;
private PublisherService publisherService;
private SubjectService subjectService;
// some code and i generated setter and getter methods
............
#RequestMapping(value="/catalogue/new.action", method=RequestMethod.GET)
public ModelAndView newMember() throws Exception {
ModelAndView mvc= null;
mvc = new ModelAndView("catalogue/catalogueForm", "catalogueForm", new CatalogueBase());
mvc.addObject("copyDetailForm", new CatalogueCopyDetails());
List<Publisher> publist = publisherService.getPublisherList();
mvc.addObject("publist", publist);
List<Subject> subjectlist = subjectService.getSubjectList();
mvc.addObject("subjectlist", subjectlist);
return mvc;
}
this is my service method :
#Override
public List<Publisher> getPublisherList() {
List<Publisher> list = publisherDAO.getPublisher();
return list;
}
#Override
public List<Subject> getSubjectList() {
List<Subject> list = subjectDAO.getSubjects();
return list;
}
this is my DAO Method:
#SuppressWarnings("unchecked")
public List<Publisher> getPublisher() {
Query qry = getSession().createQuery("from Publisher");
return qry.list();
}
#SuppressWarnings("unchecked")
public List<Subject> getSubjects() {
Query qry = getSession().createQuery("from Subject");
return qry.list();
}
finally this is my JSP page :
<form:form commandname="catalogueForm" action="${pageContext.request.contextPath}/catalogue/create.action" method="post" modelAttribute="catalogueForm">
<form:select path="publisher.id" id="publisher.id">
<form:options items="${publist}" itemValue="id" itemLabel="name" />
</form:select>
<form:select path="subject.id" id="subject.id">
<form:options items="${subjectlist}" itemValue="id" itemLabel="name" />
</form:select>
</form:form>
This is Stack Trace:
java.lang.NullPointerException
at com.easylib.elibrary.webapp.controller.catalogue.CatalogueController.newMember(CatalogueController.java:80)
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:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
You are getting the npe at line 80 of your controller, but I can't see which line that is in your question.
My guess is that you haven't wired in your services correctly and either "publisherService" or "subjectService" is null.

Exception while implementing LazyModel for primefaces datalist

I am trying to implement the lazy loading model for the primefaces datalist similar to datatable as shown here.
My initial code with the normal AJAX pagination feature works absolutely fine. However, when I try using the lazy loading model, I get the exception below when the page loads :
com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
SEVERE: Error Rendering View[/pages/index.xhtml]
java.io.NotSerializableException: java.util.ArrayList$SubList
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at java.util.HashMap.writeObject(HashMap.java:1100)
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 java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:975)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1480)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1362)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1170)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at java.util.HashMap.writeObject(HashMap.java:1100)
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 java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:975)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1480)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at com.sun.faces.renderkit.ClientSideStateHelper.doWriteState(ClientSideStateHelper.java:325)
at com.sun.faces.renderkit.ClientSideStateHelper.writeState(ClientSideStateHelper.java:173)
at com.sun.faces.renderkit.ResponseStateManagerImpl.writeState(ResponseStateManagerImpl.java:122)
at com.sun.faces.application.StateManagerImpl.writeState(StateManagerImpl.java:166)
at com.sun.faces.application.view.WriteBehindStateWriter.flushToWriter(WriteBehindStateWriter.java:225)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:418)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
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.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Here's the code of index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="/pages/templates/template.xhtml">
<ui:define name="content">
<h:form prependId="false" id="form">
<p:dataList value="#{movies.lazyMovieModel}" var="movie" id="movies" paginator="true" rows="10"
paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
type="none" paginatorAlwaysVisible="false" lazy="true">
<h:outputText value="#{movie.movieName}, #{movie.releaseYear}" style="margin-left:10px">
</h:outputText>
<br/>
</p:dataList>
</h:form>
</ui:define>
</ui:composition>
</html>
MovieListBean.java
import org.primefaces.model.LazyDataModel;
import com.clixflix.enitities.Movie;
import com.clixflix.jsf.extensions.LazyMovieDataModel;
#ManagedBean(name = "movies")
#ViewScoped
public class MovieListBean extends BaseBean implements Serializable
{
private static final long serialVersionUID = -5719443344065177588L;
private LazyDataModel<Movie> lazyMovieModel;
#PostConstruct
public void initialize() {
lazyMovieModel = new LazyMovieDataModel();
}
public LazyDataModel<Movie> getLazyMovieModel()
{
List<Movie> movieList = getServiceLocator().getMovieService().getMovieList();
((LazyMovieDataModel) lazyMovieModel).setMovieList(movieList);
return lazyMovieModel;
}
}
LazyMovieDataModel.java (LazyModel implementation)
public class LazyMovieDataModel extends LazyDataModel<Movie>
{
private static final long serialVersionUID = 8745562148994455749L;
private List<Movie> movieList;
public LazyMovieDataModel() {
this.movieList = Collections.emptyList();
}
#Override
public List<Movie> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
// Sorting
if (null != sortField) {
LazySorter sorter = new LazySorter(sortField, sortOrder);
Collections.sort(movieList, sorter);
sorter = null;
}
// RowCount
int rowCount = movieList.size();
this.setRowCount(rowCount);
// Pagination
if (rowCount > pageSize) {
return movieList.subList(first, (first + pageSize));
}
else {
return movieList;
}
}
private class LazySorter implements Comparator<Movie>
{
private String sortField;
private SortOrder sortOrder;
LazySorter(String sortField, SortOrder sortOrder) {
this.sortField = sortField;
this.sortOrder = sortOrder;
}
#SuppressWarnings("unchecked")
#Override
public int compare(Movie movie1, Movie movie2) {
Object value1 = null, value2 = null;
try {
value1 = Movie.class.getField(this.sortField).get(movie1);
value2 = Movie.class.getField(this.sortField).get(movie2);
int value = ((Comparable<Object>) value1).compareTo(value2);
return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
}
catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
e.printStackTrace();
return 0;
}
}
}
public void setMovieList(List<Movie> movieList) {
this.movieList = movieList;
}
}
I am assuming the exception is at this line:
return movieList.subList(first, (first + pageSize));
Could anyone please guide me as to what am I missing?
Also, I observe in the logs, that when I use the lazymodel, the DB gets queried three times but when I use the normal AJAX pagination, the DB is queried only once :|
UPDATE: I figured out the reason for the DB being queried 3 times. It was because I was calling my service in the getter of the LazyModel instead of only in the load method.
I made the following changes in the classes:
LazyMovieDataModel.java
public class LazyMovieDataModel extends LazyDataModel<Movie>
{
private static final long serialVersionUID = 8745562148994455749L;
public LazyMovieDataModel() {}
#Override
public List<Movie> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
List<Movie> movieList = getServiceLocator().getMovieService().getMovieList(first, (first + pageSize));
// RowCount
int rowCount = ((Number)getServiceLocator().getMovieService().getMovieCount()).intValue();
this.setRowCount(rowCount);
}
}
LazyModel getter in MovieListBean.java
/* Removed PostConstruct init method */
public LazyDataModel<Movie> getLazyMovieModel()
{
return lazyMovieModel;
}
The above changes work fine on the initial page load. However, when I hit the next page button (or any pagination button) I get an NPE for getServiceLocator() in the load method.
The serviceLocator is a protected access modified managed property inherited from BaseBean and injected using Spring.
Any reason why the getter returns null on subsequent invokes ???
ArrayList$SubList is a problem. The subList returned does not implement serializable.
Try using:
return new ArrayList(movieList.subList(first, (first + pageSize)));
Same problem in this link.There are 2 load methods in LazyDataModel:
public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
throw new UnsupportedOperationException("Lazy loading is not implemented.");
}
public List<T> load(int first, int pageSize, List<SortMeta> multiSortMeta,Map<String,String> filters) {
throw new UnsupportedOperationException("Lazy loading is not implemented.");
}
This is where the error is thrown. You are using multisort, so you should override the second.Default method is the first one.

org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions

Upon deleting an entity from the database I get the following exception:
org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
at org.hibernate.collection.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:410)
at org.hibernate.event.def.OnUpdateVisitor.processCollection(OnUpdateVisitor.java:43)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:101)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:61)
at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:55)
at org.hibernate.event.def.AbstractVisitor.process(AbstractVisitor.java:123)
at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:101)
at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:52)
at org.hibernate.impl.SessionImpl.fireDelete(SessionImpl.java:767)
at org.hibernate.impl.SessionImpl.delete(SessionImpl.java:745)
at org.springframework.orm.hibernate3.HibernateTemplate$25.doInHibernate(HibernateTemplate.java:790)
at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:372)
at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:784)
at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:780)
at pl.edu.agh.adam.core.projects.dao.TagDAO.delete(TagDAO.java:98)
at pl.edu.agh.adam.core.projects.ProjectService.deleteTag(ProjectService.java:109)
at pl.edu.agh.adam.core.projects.web.TagPresenter.deleteTag(TagPresenter.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at org.apache.myfaces.view.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:83)
at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:88)
at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:100)
at javax.faces.component.UICommand.broadcast(UICommand.java:120)
at javax.faces.component.UIData.broadcast(UIData.java:708)
at javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:890)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:234)
at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1202)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:623)
at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:35)
at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:143)
at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:93)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
I've dug deep and tried numerous solutions from the hibernate forum, but still I don't know what's going on and where the sessions are opened. The conditions under which this problem occurs:
First: OpenSessionInViewFilter - I've asked about it here. Everything seemed to work fine, but the deleting stopped all of a sudden the following day and all I've done is - I've added a non-connected class to a non-connected package.
<!-- Hibernate OpenSession Filter -->
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
Second: three-tier architecture. Here are the classes and the JSF page:
#Entity
#Table(name = "tag")
public class Tag implements Serializable {
private static final long serialVersionUID = 1L;
#ManyToMany(mappedBy = "tags", targetEntity = Project.class)
List<Project> projects = new ArrayList<Project>();
#Transient
public static final String PROP_ID = "id";
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "tag_id")
private Long id;
#Transient
public static final String PROP_NAME = "name";
#Column(name = "name", length = 25, unique = true)
private String name;
}
public class TagDAO extends HibernateDaoSupport implements ITagDAO {
#Override
public void create(Tag tag) {
getHibernateTemplate().save(tag);
}
#Override
public Tag getTag(String name){
Tag group = null;
DetachedCriteria criteria = DetachedCriteria.forClass(Tag.class);
criteria.add(Restrictions.eq("name", name));
List<Tag> tags = getHibernateTemplate().findByCriteria(criteria);
if ((tags != null) && (tags.size() > 0)) {
group = (Tag)tags.get(0);
}
return group;
}
#Override
public Tag getTag(Long id){
Tag group = null;
List<Tag> groups = getHibernateTemplate().find(
"from Tag where id = ?", id);
if ((groups != null) && (groups.size() > 0)) {
group = (Tag)groups.get(0);
}
return group;
}
#Override
public List<Tag> getTags(){
List<Tag> ret = getHibernateTemplate().find("from Tag");
System.out.println("Dao got "+ret.size()+" tags");
return ret;
}
#Override
public Integer getTagCount() {
DetachedCriteria criteria = DetachedCriteria.forClass(Tag.class);
criteria.setProjection(Projections.rowCount());
return (Integer)(getHibernateTemplate().findByCriteria(criteria).get(0));
}
#Override
public void delete(Tag group) {
getHibernateTemplate().delete(group);
}
#Override
public void update(Tag group) {
getHibernateTemplate().update(group);
}
#Override
public List<Tag> getTags(Integer first, Integer resultsPerPage,
String order, Boolean asc) {
DetachedCriteria criteria = DetachedCriteria.forClass(Tag.class);
if (asc){
criteria.addOrder(Order.asc(order));
}else{
criteria.addOrder(Order.desc(order));
}
return (List<Tag>)getHibernateTemplate().findByCriteria(criteria, first, resultsPerPage);
}
}
public class ProjectService implements IProjectService {
// Beans used by this service.
private IProjectDAO projectDao;
private ITagDAO tagDao;
#Override
public void createProject(Project project) throws AlreadyExistsException {
if (projectDao.getProject(project.getName()) != null) {
throw new AlreadyExistsException();
}
projectDao.addProject(project);
}
#Override
public List<Project> getProjects(Integer first, Integer howMany, String order,
boolean asc) {
return projectDao.getProjects(first, howMany, order, asc);
}
#Override
public Integer getProjectCount(){
return projectDao.getProjectCount();
}
#Override
public List<Project> getProjects() {
return projectDao.getAllProjects();
}
#Override
public void deleteProject(Long id) {
projectDao.removeProject(id);
}
#Override
public List<Tag> getTags() {
return tagDao.getTags();
}
#Override
public Tag getTag(String name){
return tagDao.getTag(name);
}
#Override
public void createTag(Tag tag) throws AlreadyExistsException {
if (tagDao.getTag(tag.getName()) != null) {
throw new AlreadyExistsException();
}
tagDao.create(tag);
}
#Override
public void deleteTag(Long id) {
tagDao.delete(tagDao.getTag(id));
}
#Override
public void updateTag(Tag tag) {
tagDao.update(tag);
}
}
#ManagedBean(name = "tagPresenter")
#RequestScoped
public class TagPresenter {
private List<Tag> tags;
private IProjectService projectService;
private Tag tag;
public void setTag(Tag tag) {
this.tag= tag;
}
public Tag getTag() {
return tag;
}
public TagPresenter() {
projectService = (IProjectService)ServiceFinder.getInstance()
.findBean("projectService");
tags = projectService.getTags();
}
private void refresh() {
tags = projectService.getTags();
}
public List<Tag> getTags() {
refresh();
return tags;
}
public void deleteTag() {
projectService.deleteTag(tag.getId());
}
}
finally the webpage:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.prime.com.tr/ui">
<ui:composition template="/templates/template.xhtml">
<ui:define name="head">
<title>Tags</title>
<link rel="stylesheet" type="text/css" href="#{facesContext.externalContext.requestContextPath}/styles/style.css"/>
</ui:define>
<ui:define name="content">
<h:form name="commandForm">
<p:dataTable var="tag" name="tagsList" value="${tagPresenter.tags}" paginator="true" rows="10" >
<p:column sortBy="#{tag.id}">
<f:facet name="header">
<h:outputText value="Id" />
</f:facet>
<h:outputText value="#{tag.id}" />
</p:column>
<p:column sortBy="#{tag.name}">
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{tag.name}" />
</p:column>
<p:column>
<h:commandLink action="#{tagDisplayer.showTag}" value="Modify">
<f:setPropertyActionListener target="#{tagDisplayer.tag}" value="#{tag}"/>
</h:commandLink>
<h:commandLink action="#{tagPresenter.deleteTag}" value="Delete">
<f:setPropertyActionListener target="#{tagPresenter.tag}" value="#{tag}"/>
</h:commandLink>
</p:column>
</p:dataTable>
</h:form>
<p:messages id="deletingError" showDetail="true"/>
</ui:define>
</ui:composition>
</html>
How is this problem caused and how can I solve it?
Fixes for this vary widely; it can be caused by problems like
bad session handling in your framework configuration
bad cascade settings, incorrect persistence settings
forgetting initialization of an Collection stored in a #ManyToOne database relation.
Make sure to check thoroughly for these cases in your mapping/hibernate configurations - before wasting hours. :D
Take a look at the HibernateTemplate chapter in the Spring documentation. Take a look at implementing a callback approach to access the session.
public void delete(final Tag group) throws Exception {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Object groupObj = session.load(Tag.class, group.getId());
session.delete(groupObj);
return null;
}
};
getHibernateTemplate().execute(callback);
}
If the above is not what you are looking for you can still do a traditional approach as mentioned further down in the Spring documentation. In this approach don't use the HibernateTemplate to delete the object but use the Session from the HibernateDaoSupport to handle the delete.
public void delete(Tag group) throws Exception {
Session session = getSession(false);
Object groupObj = session.load(Tag.class, group.getId());
session.delete(groupObj);
}
This can be caused by calling session.disconnect() instead of session.close().

Resources