I am trying to query the subclass by the parent attributes. However hibernate always try to map the query result to parent class.
Framework used: JPA 2.0, Hibernate 3, Spring 3
Exception thrown:
org.springframework.orm.hibernate3.HibernateObjectRetrievalFailureException: Object with id: com.hkbea.zpm.entity.PositionPk#1dee9de was not of the specified subclass: com.hkbea.zpm.entity.FundPosition (loaded object was of wrong class class com.hkbea.zpm.entity.Position); nested exception is org.hibernate.WrongClassException: Object with id: com.hkbea.zpm.entity.PositionPk#1dee9de was not of the specified subclass: com.hkbea.zpm.entity.FundPosition (loaded object was of wrong class class com.hkbea.zpm.entity.Position)
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:666)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.convertHibernateAccessException(AbstractSessionFactoryBean.java:303)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.translateExceptionIfPossible(AbstractSessionFactoryBean.java:282)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy93.getFundListByAccountNumber(Unknown Source)
at com.hkbea.zpm.service.impl.OnlineInterfaceServiceImpl.adjustCashForRedeemUT(OnlineInterfaceServiceImpl.java:1224)
at com.hkbea.zpm.service.impl.OnlineInterfaceServiceImpl.getTRB(OnlineInterfaceServiceImpl.java:248)
at com.hkbea.zpm.service.impl.OnlineInterfaceServiceImpl.getTRB(OnlineInterfaceServiceImpl.java:219)
at com.hkbea.zpm.service.impl.OnlineInterfaceServiceImpl.calculateHandler(OnlineInterfaceServiceImpl.java:158)
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.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy94.calculateHandler(Unknown Source)
at com.hkbea.zpm.controller.OnlineInterfaceController.calculate(OnlineInterfaceController.java:90)
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.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at com.hkbea.zpm.ext.spring.ZPMAnnotationMethodHandlerAdapter.invokeHandlerMethod(ZPMAnnotationMethodHandlerAdapter.java:429)
at com.hkbea.zpm.ext.spring.ZPMAnnotationMethodHandlerAdapter.handle(ZPMAnnotationMethodHandlerAdapter.java:417)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at com.hkbea.zpm.session.ZPMLoginFilter.doFilter(ZPMLoginFilter.java:68)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1136)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
I've set the hibernate.show_sql to true and checked the sql seems alright and is expected when i try to execute in sql client.
select
fundpositi0_.CATEGORY as CATEGORY49_,
fundpositi0_.MAIN_ACCOUNT_NUMBER as MAIN1_49_,
fundpositi0_.REFERENCE as REFERENCE49_,
fundpositi0_1_.ACCOUNT_NUMBER as ACCOUNT3_49_,
fundpositi0_1_.ACCOUNT_NUMBER_EXT as ACCOUNT4_49_,
fundpositi0_1_.ACTIVE_FLAG as ACTIVE5_49_,
fundpositi0_1_.BASE_MARKET_VALUE as BASE6_49_,
fundpositi0_1_.CREATE_TIMESTAMP as CREATE7_49_,
fundpositi0_1_.CREATE_USER as CREATE8_49_,
fundpositi0_1_.CURRENCY as CURRENCY49_,
fundpositi0_1_.DESCRIPTION as DESCRIP10_49_,
fundpositi0_1_.EXCHANGE_RATE as EXCHANGE11_49_,
fundpositi0_1_.LDS_TYPE as LDS12_49_,
fundpositi0_1_.MARKET_VALUE as MARKET13_49_,
fundpositi0_1_.NEW_RISK_RATING as NEW14_49_,
fundpositi0_1_.QUANTITY as QUANTITY49_,
fundpositi0_1_.RISK_RATING as RISK16_49_,
fundpositi0_1_.UNIT_PRICE as UNIT17_49_,
fundpositi0_1_.UPDATE_TIMESTAMP as UPDATE18_49_,
fundpositi0_1_.UPDATE_USER as UPDATE19_49_,
fundpositi0_.AVAILABLE_BALANCE as AVAILABLE1_75_,
fundpositi0_.AVERAGE_COST as AVERAGE2_75_,
fundpositi0_.BASE_PROFIT_LOSS as BASE3_75_,
fundpositi0_.INSTRUMENT_NAME as INSTRUMENT4_75_,
fundpositi0_.ISIN_CODE as ISIN5_75_,
fundpositi0_.LAST_QUANTITY as LAST6_75_,
fundpositi0_.PROFIT_LOSS as PROFIT7_75_,
fundpositi0_.QUANTITY_HELD as QUANTITY8_75_,
fundpositi0_.SCS_SECURITY_CODE as SCS9_75_
from
PBWMS_FUND_POS fundpositi0_,
PBWMS_POS fundpositi0_1_
where
fundpositi0_.CATEGORY=fundpositi0_1_.CATEGORY
and fundpositi0_.MAIN_ACCOUNT_NUMBER=fundpositi0_1_.MAIN_ACCOUNT_NUMBER
and fundpositi0_.REFERENCE=fundpositi0_1_.REFERENCE
and fundpositi0_1_.ACTIVE_FLAG='A'
and fundpositi0_1_.ACCOUNT_NUMBER=?
I've tried to change the parent class to abstract, but hibernate will throw exception for failed to instantiate object of abstract class.
Caused by: org.hibernate.InstantiationException: Cannot instantiate abstract class or interface: com.hkbea.zpm.entity.Position
I've also searched some other post said, the cascade mode need to be set for many-to-one property. So i have tried but still not working.
Query:
(List<FundPosition>) sessionFactory.getCurrentSession()
.createQuery("from FundPosition where activeFlag='A' and accountNumber=?")
.setString(0, accountNumber)
.list();
Parent Class:
#Entity
#Table(name="PBWMS_POS")
#Inheritance(strategy=InheritanceType.JOINED)
public class Position extends BaseEntityObject
{
private static final long serialVersionUID = -5370267130957236544L;
#Id
protected PositionPk pk;
#ManyToOne(cascade = CascadeType.DETACH)
#JoinColumn(name="MAIN_ACCOUNT_NUMBER", insertable=false, updatable=false)
protected CustomerAccount customerAccount;
#Column(name="ACCOUNT_NUMBER", nullable=false)
protected String accountNumber;
#Column(name="ACCOUNT_NUMBER_EXT", nullable=false)
protected String accountNumberExt;
#Column(name="DESCRIPTION", nullable=false)
protected String description;
#Column(name="CURRENCY", nullable=false)
protected String currency;
#Column(name="QUANTITY")
protected BigDecimal quantity;
#Column(name="UNIT_PRICE")
protected BigDecimal unitPrice;
#Column(name="EXCHANGE_RATE", scale=6, precision=8)
protected BigDecimal exchangeRate;
#Column(name="MARKET_VALUE")
protected BigDecimal marketValue;
#Column(name="BASE_MARKET_VALUE")
protected BigDecimal baseMarketValue;
#Column(name="ACTIVE_FLAG", nullable=false, length=1)
protected String activeFlag;
#Column(name="CREATE_USER", nullable=false)
protected String createUser;
#Column(name="CREATE_TIMESTAMP")
protected Timestamp createTimestamp;
#Column(name="UPDATE_USER")
protected String updateUser;
#Column(name="UPDATE_TIMESTAMP")
protected Timestamp updateTimestamp;
#Column(name="RISK_RATING")
protected String riskRating;
#Column(name="NEW_RISK_RATING")
protected String newRiskRating;
#Column(name="LDS_TYPE")
protected String ldsType;
//getters and setters...
}
Child Class:
#Entity
#Table(name="PBWMS_FUND_POS")
public class FundPosition extends Position
{
private static final long serialVersionUID = -8143748295075339416L;
#Column(name="ISIN_CODE", nullable=false)
private String isinCode;
#Column(name="INSTRUMENT_NAME", nullable=false)
private String instrumentName;
#Column(name="SCS_SECURITY_CODE", nullable=false)
private String scsSecurityCode;
#Column(name="AVAILABLE_BALANCE", nullable=false)
private BigDecimal availableBalance;
#Column(name="QUANTITY_HELD", nullable=false)
private BigDecimal quantityHeld;
#Column(name="AVERAGE_COST")
private BigDecimal averageCost;
#Column(name="PROFIT_LOSS")
private BigDecimal profitLoss;
#Column(name="BASE_PROFIT_LOSS")
private BigDecimal baseProfitLoss;
#Column(name="LAST_QUANTITY")
private BigDecimal lastQuantity;
//getters and setters...
}
Composite Key Class:
#Embeddable
public class PositionPk implements Serializable
{
private static final long serialVersionUID = -9161644029517397019L;
#Column(name="MAIN_ACCOUNT_NUMBER")
protected String mainAccountNumber;
#ManyToOne(cascade = CascadeType.DETACH)
#JoinColumn(name="CATEGORY")
protected Category category;
#Column(name="REFERENCE")
protected String reference;
//equals, getters and setters...
}
BaseEntityObject Class:
...
import net.sf.gilead.pojo.java5.LightEntity;
public abstract class BaseEntityObject extends LightEntity
{
private static final long serialVersionUID = -7453050794164673008L;
#Transient
public Object getUnderlyingValue()
{
return null;
}
public void setUnderlyingValue(Object obj)
{
}
#Transient
public String getDebugString()
{
return null;
}
public void setDebugString(String str)
{
}
#Override
public abstract boolean equals(Object obj);
}
Update on 2019-08-15,
Also tried to add following annotations in subclass, still not working
#PrimaryKeyJoinColumns({
#PrimaryKeyJoinColumn(name="MAIN_ACCOUNT_NUMBER", referencedColumnName="MAIN_ACCOUNT_NUMBER"),
#PrimaryKeyJoinColumn(name="REFERENCE", referencedColumnName="REFERENCE"),
#PrimaryKeyJoinColumn(name="CATEGORY", referencedColumnName="CATEGORY")
})
Related
Group.java
package com.keating.model;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
#Entity
#Table(name = "t_group")
#JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Group implements Serializable {
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid")
#Column(name = "uuid", unique = true)
private String uuid;
#Column(name = "name", nullable = false, unique = true)
private String name;
#Column(name = "description", nullable = false, unique = false)
private String description;
#ManyToOne
#JoinColumn(name = "creatorUUID", nullable = false, unique = false)
private User creator;
#Column(name = "create_time", nullable = false)
private Date time = new Date();
public Group() {
}
public Group(String name, String description) {
this.name = name;
this.description = description;
}
public Group(String name, String description, User creator) {
this.name = name;
this.description = description;
this.creator = creator;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public User getCreator() {
return creator;
}
public void setCreator(User creator) {
this.creator = creator;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
And there is my method.
public Group getInfo(String groupUUID) {
String hql = "SELECT group.uuid, group.name, group.description, group.time FROM Group group WHERE group.uuid=?";
Query query = this.getCurrentSession().createQuery(hql);
query.setParameter(0, groupUUID);
return (Group) query.uniqueResult();
}
And I think it is ok, but there are some exceptions:
HTTP Status 500 – Internal Server Errorh1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}HTTP Status 500 – Internal Server ErrorType Exception ReportMessage Request processing failed; nested exception is java.lang.ClassCastException: java.base/[Ljava.lang.Object; cannot be cast to com.keating.model.GroupDescription The server encountered an unexpected condition that prevented it from fulfilling the request.Exceptionorg.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: java.base/[Ljava.lang.Object; cannot be cast to com.keating.model.Group
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Root Causejava.lang.ClassCastException: java.base/[Ljava.lang.Object; cannot be cast to com.keating.model.Group
com.keating.dao.impl.GroupDaoImpl.getInfo(GroupDaoImpl.java:26)
com.keating.service.impl.GroupServiceImpl.getInfo(GroupServiceImpl.java:23)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:564)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
com.sun.proxy.$Proxy37.getInfo(Unknown Source)
com.keating.controller.GroupController.getInfo(GroupController.java:56)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:564)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Note The full stack trace of the root cause is available in the server logs.Apache Tomcat/9.0.2
Drop the list of fields you're trying to lookup
String hql = "FROM Group group WHERE group.uuid=?";
In my database, I have three tables: Hotels, Facilities and Images. Hotels table has "One to Many Relationship" with both tables: Facilities and Images. Facilities and Images table, both have hotels column as a Foreign Key.
While fetching details of a hotel, I want to retrieve Facilities and Images for the hotel. However I receive the org.hibernate.type.SerializationException
Exception stacktrace:
SEVERE: Servlet.service() for servlet [dispatcher] in context with path threw exception [Request processing failed; nested exception is org.hibernate.type.SerializationException: could not deserialize] with root cause
java.io.StreamCorruptedException: invalid stream header: 32303136
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:328)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:318)
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:237)
at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:306)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:155)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:130)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:44)
at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:71)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:64)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:267)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:263)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:338)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2969)
at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.loadFromResultSet(EntityReferenceInitializerImpl.java:324)
at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.hydrateEntityState(EntityReferenceInitializerImpl.java:251)
at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.readRow(AbstractRowReader.java:107)
at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:129)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:138)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:100)
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:693)
at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:92)
at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1897)
at org.hibernate.collection.internal.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:683)
at org.hibernate.engine.internal.StatefulPersistenceContext.initializeNonLazyCollections(StatefulPersistenceContext.java:890)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:359)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
at com.holidify.app.dao.impl.HotelsDaoImpl.getMergedResponse(HotelsDaoImpl.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy53.getMergedResponse(Unknown Source)
at com.holidify.app.service.impl.HotelsServiceImpl.getHotelsMergedResponse(HotelsServiceImpl.java:104)
at com.holidify.app.controller.HotelsController.searchDynamicHotels(HotelsController.java:192)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Hotels.java
#Entity
#Table(name="Hotels")
public class Hotels implements Serializable{
private static final long serialVersionUID = -5573648649418161369L;
private Set<Facilities> facilities;
private Set<Images> images;
private int hotelId;
//other fields
//other getter and setters
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "hotels")
public Set<Images> getImages() {
return images;
}
public void setImages(Set<Images> images) {
this.images = images;
}
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "hotels")
public Set<Facilities> getFacilities() {
return facilities;
}
public void setFacilities(Set<Facilities> facilities) {
this.facilities = facilities;
}
}
Facilities.java
#Entity
#Table(name="Facilities")
public class Facilities implements Serializable{
private static final long serialVersionUID = -552767579935736531L;
private Integer facilityId;
private String facilityName;
private Timestamp timeStamp;
private Hotels hotels;
//other getter and setters
#Id
#Column(name = "facilityId", insertable = true, updatable = true)
#GeneratedValue(strategy=GenerationType.AUTO)
#ManyToOne
#JoinColumn(name="hotelId")
public Hotels getHotels() {
return hotels;
}
public void setHotels(Hotels hotels) {
this.hotels = hotels;
}
public Facilities() {
super();
// TODO Auto-generated constructor stub
}
public Facilities(String facilityName) {
super();
this.facilityName = facilityName;
}
}
Images.java
#Entity
#Table(name="Images")
public class Images implements Serializable {
private static final long serialVersionUID = -4318294155906543400L;
private Integer imageId;
private String imageURL;
private Timestamp timeStamp;
private Hotels hotels;
//other getter and setters
#ManyToOne
#JoinColumn(name="hotelId")
public Hotels getHotels() {
return hotels;
}
public void setHotels(Hotels hotels) {
this.hotels = hotels;
}
public Images() {
super();
// TODO Auto-generated constructor stub
}
public Images(String imageUrl) {
super();
this.imageURL = imageUrl;
}
}
Thanks in advance.
In some cases this error is also caused when you use JDK 8 java.time.LocalDateTime with hibernate and don't have a Converter for this registered. (This is not the case in the OP's question, but other people might stumble about this.)
Looks like Hibernate try to deserialize a column that holds not serialized data. Hibernate thinks that this column has VARBINARY format. I think it is Timestamp property or other object property. Try to comment all columns in Facilities and Images except id and hotels.
You can use java SQL Date for date option and try again. Basically it happens sometimes when you try to convert date. So you can try with java SQL Date.
Below is some code for background:
InitiativeProfileQuestion.java:
#Entity
#Table
public class InitiativeProfileQuestion implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(nullable = false)
private String question;
#Column
private String description;
#Column
private int sortOrder;
#OneToMany(mappedBy = "initiativeProfileQuestion", fetch = FetchType.LAZY)
private List<InitiativeProfileAnswer> answers;
public List<InitiativeProfileAnswer> getAnswers() {
return answers;
}
public void setAnswers(List<InitiativeProfileAnswer> answers) {
this.answers = answers;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getSortOrder() {
return sortOrder;
}
public void setSortOrder(int sortOrder) {
this.sortOrder = sortOrder;
}
}
InitiativeProfileAnswer.java:
#Entity
#Table
public class InitiativeProfileAnswer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column
private String answer;
#Column
private int sortOrder;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "initiativeProfileQuestionId")
#JsonIgnore
private InitiativeProfileQuestion initiativeProfileQuestion;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public int getSortOrder() {
return sortOrder;
}
public void setSortOrder(int sortOrder) {
this.sortOrder = sortOrder;
}
public InitiativeProfileQuestion getInitiativeProfileQuestion() {
return initiativeProfileQuestion;
}
public void setInitiativeProfileQuestion(InitiativeProfileQuestion initiativeProfileQuestion) {
this.initiativeProfileQuestion = initiativeProfileQuestion;
}
}
InitiativeProfileQuestionRepository.java:
public interface InitiativeProfileQuestionRepository extends JpaRepository<InitiativeProfileQuestion, Long> {
#Query("select ipa from InitiativeProfileQuestion ipa join fetch ipa.answers")
public List<InitiativeProfileQuestion> getAllQuestions();
}
InitiativeProfileService.java:
#Service
public class InitiativeProfileService {
#Autowired
private InitiativeProfileQuestionRepository initiativeProfileQuestionRepository;
public List<InitiativeProfileQuestion> getAllQuestions() {
return initiativeProfileQuestionRepository.findAll();
}
public List<InitiativeProfileQuestion> getAllQuestionsFetch() {
return initiativeProfileQuestionRepository.getAllQuestions();
}
}
BaseController.java:
#RestController
#RequestMapping("/api")
public class BaseController {
#Autowired
InitiativeProfileService initiativeProfileService;
#RequestMapping("/question")
public List<InitiativeProfileQuestion> getQuestions() {
return initiativeProfileService.getAllQuestions();
}
#RequestMapping("/questionFetch")
public List<InitiativeProfileQuestion> getQuestionsFetch() {
return initiativeProfileService.getAllQuestionsFetch();
}
}
Calling getQuestions() in my BaseController returns a "could not initialize proxy - no Session" error. However, calling getQuestionsFetch() in my BaseController loads just fine.
I want it to work in a way that if I call getQuestions(), the object will be returned with NO answers (since the lazy loaded object will not be called anywhere). However, it just gives me an error. If I'm doing a query with a join fetch, it works by showing the answers as well (expected behavior).
What am I doing wrong? I tried #Transactional in different places with no luck. I also have no .xml files- everything so far is done using annotations.
The error I get is:
exception
org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: failed to lazily initialize a collection of role: com.testApp.domain.InitiativeProfileQuestion.answers, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.testApp.domain.InitiativeProfileQuestion["answers"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.testApp.domain.InitiativeProfileQuestion.answers, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.testApp.domain.InitiativeProfileQuestion["answers"])
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:238)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:101)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:185)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
root cause
com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.testApp.domain.InitiativeProfileQuestion.answers, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.testApp.domain.InitiativeProfileQuestion["answers"])
com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:210)
com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:177)
com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:187)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:647)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase._serializeWithObjectId(BeanSerializerBase.java:558)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:145)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183)
com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:128)
com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1902)
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:101)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:185)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
For an exception in case of lazy loading you must be trying to fetch the associated objects outside the session. Either change the lazy loading to eager or put your code which is fetching the associated object inside the session.
For e.g:
public void test() {
Session session = HibernateUtil.currentSession();
session.beginTransaction();
Vehicle vehicle= (Vehicle) session.get(Vehicle.class, 2);
System.out.println(vehicle.getVehicleName());
session.getTransaction().commit();
session.close();
System.out.println(vehicle.getVehicleName()); //No exception here
System.out.println(vehicle.getUser().getUserName());
// Exception here change the loading to EAGER or put this line of code within the session above. Put it before session.close() or before session.getTransaction().commit();
}
As you can see from the stacktrace, the error occurs when Jackson is trying to access the lazily loaded object in order to serialize it to JSON. At this time, the spring transaction has already completed, and the Hibernate session closed, which is why Hibernate can no longer load that object.
If you do not intend that field to be serialized, you might wish to use #JsonIgnore, or Spring's Jackson Serialization View Support.
Entity class:
package com.rapid.admin.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* LoginHistory entity. #author MyEclipse Persistence Tools
*/
#Entity
#Table(name = "login_history", catalog = "project")
public class LoginHistory implements java.io.Serializable {
// Fields
private Integer id;
private String username;
private Timestamp loginTime;
private Timestamp logoutTime;
private Boolean status;
private String timeId;
// Constructors
/** default constructor */
public LoginHistory() {
}
/** full constructor */
public LoginHistory(String username, Timestamp loginTime,
Timestamp logoutTime, Boolean status, String timeId) {
this.username = username;
this.loginTime = loginTime;
this.logoutTime = logoutTime;
this.status = status;
this.timeId = timeId;
}
// Property accessors
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "username", length = 45)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "login_time", length = 19)
public Timestamp getLoginTime() {
return this.loginTime;
}
public void setLoginTime(Timestamp loginTime) {
this.loginTime = loginTime;
}
#Column(name = "logout_time", length = 19, updatable= true)
public Timestamp getLogoutTime() {
return this.logoutTime;
}
public void setLogoutTime(Timestamp logoutTime) {
this.logoutTime = logoutTime;
}
#Column(name = "status")
public Boolean getStatus() {
return this.status;
}
public void setStatus(Boolean status) {
this.status = status;
}
#Column(name = "time_id", length = 45)
public String getTimeId() {
return this.timeId;
}
public void setTimeId(String timeId) {
this.timeId = timeId;
}
Hibernate query :
sessionFactory.getCurrentSession().beginTransaction();
Criteria criteria =
sessionFactory.getCurrentSession().createCriteria(LoginHistory.class);
criteria.add(Restrictions.eq("id",id));
LoginHistory loginHistory = new LoginHistory();
loginHistory.setLogoutTime(AdminUtil.getTimeStamp());
sessionFactory.getCurrentSession().update(loginHistory);
Error on console:
org.hibernate.TransientObjectException: The given object has a null identifier: com.rapid.admin.entity.LoginHistory
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.getUpdateId(DefaultSaveOrUpdateEventListener.java:272)
at org.hibernate.event.def.DefaultUpdateEventListener.getUpdateId(DefaultUpdateEventListener.java:69)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:240)
at org.hibernate.event.def.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireUpdate(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:580)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:572)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:342)
at $Proxy21.update(Unknown Source)
at com.rapid.admin.daoimpl.LoginDaoImpl.updateLogoutTime(LoginDaoImpl.java:117)
at com.rapid.admin.serviceimpl.LoginServiceImpl.updateLogoutTime(LoginServiceImpl.java:53)
at com.rapid.admin.controller.LoginController.logout(LoginController.java:87)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
org.hibernate.TransientObjectException: The given object has a null identifier: com.rapid.admin.entity.LoginHistory
I guess you should write like this : (by considering you want to update LoginHistory which is already in DB having id that you are passing)
hibernate query :
sessionFactory.getCurrentSession().beginTransaction();
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(LoginHistory.class);
criteria.add(Restrictions.eq("id",id));
LoginHistory loginHistory = (LoginHistory)criteria.uniqueResult();
loginHistory.setLogoutTime(AdminUtil.getTimeStamp());
sessionFactory.getCurrentSession().update(loginHistory);
I am very new to JSF and I tried a crud operation first to proceed the further in my project.But I have a struck up here, while inserting data into table.Also spend lot of time in this, but cant get out from this. Hope some one could shoot my mistake. I am starting from my error report on console and followed by the classes.
My stack trace as follows:
Exception during request processing:
Caused by javax.ejb.EJBTransactionRolledbackException with message: ""
org.jboss.ejb3.tx.Ejb3TxPolicy.handleInCallerTx(Ejb3TxPolicy.java:87)
org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:210)
org.jboss.ejb3.stateless.StatelessLocalProxy.invoke(StatelessLocalProxy.java:84)
$Proxy256.saveOrUpdate(Unknown Source)
org.jboss.seam.intercept.ClientSideInterceptor.invoke(ClientSideInterceptor.java:54)
org.javassist.tmp.java.lang.Object_$$_javassist_seam_21.saveOrUpdate(Object_$$_javassist_seam_21.java)
com.ermms.clrp.loginhistory.LoginhistoryActionImpl.create(LoginhistoryActionImpl.java:47)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
org.jboss.ejb3.stateless.StatelessLocalProxy.invoke(StatelessLocalProxy.java:84)
$Proxy165.create(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
org.primefaces.application.CleanupActionListener.processAction(CleanupActionListener.java:42)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
java.lang.Thread.run(Thread.java:662)
Caused by java.lang.NullPointerException with message: ""
com.ermms.clrp.dto.loginhistory.LoginhistoryMapper.mapLoginhistoryEntity(LoginhistoryMapper.java:17)
com.ermms.clrp.service.loginhistory.LoginhistoryServiceImpl.saveOrUpdate(LoginhistoryServiceImpl.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
sun.reflect.GeneratedMethodAccessor84.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:106)
org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:240)
org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:210)
org.jboss.ejb3.stateless.StatelessLocalProxy.invoke(StatelessLocalProxy.java:84)
$Proxy256.saveOrUpdate(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
org.javassist.tmp.java.lang.Object_$$_javassist_seam_21.saveOrUpdate(Object_$$_javassist_seam_21.java)
com.ermms.clrp.loginhistory.LoginhistoryActionImpl.create(LoginhistoryActionImpl.java:47)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
sun.reflect.GeneratedMethodAccessor84.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
$Proxy165.create(Unknown Source)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
java.lang.Thread.run(Thread.java:662)
The xhtml page I used for insert the date:
<ui:define name="main-container">
<div class="panel-content">
<h:form class="input-list" id="creatuser" style="width:100%;">
<h:panelGrid border="1" class="creatUserDetailsTable">
<f:facet name="header">
<h:outputText value="User Login History"
style="font-size: 23px; font-weight: bold; color: threeddarkshadow;" />
</f:facet>
<s:decorate id="nameDec" template="../../../secure/edit.xhtml">
<ui:define name="label">Name:</ui:define>
<h:inputText tabindex="1" id="amount" type="text"
class="miniusername clp"
value="#{loginhistoryAction.currentLoginhistory.name}" required="true">
<f:validateLength minimum="3" maximum="20" />
</h:inputText>
</s:decorate>
</h:panelGrid>
<h:commandButton value="Save" tabindex="20" class="usersubmit"
action="#{loginhistoryAction.create}">
</h:commandButton>
</h:form>
<h:messages globalOnly="true" />
</div>
</ui:define>
Interface used :
#Local
public interface LoginhistoryAction extends Serializable {
public String create();
public String initCurrentLoginhistory();
public void setCurrentLoginhistory(Loginhistory currentLoginhistory);
public Loginhistory getCurrentLoginhistory();
}
The action class implements the above interface:
#Name("loginhistoryAction")
#Stateless
#AutoCreate
public class LoginhistoryActionImpl implements LoginhistoryAction {
#Out(value = "currentLoginhistory", scope = ScopeType.CONVERSATION)
#In(value = "currentLoginhistory", scope = ScopeType.CONVERSATION, required = false)
private Loginhistory currentLoginhistory;
public Loginhistory getCurrentLoginhistory() {
return currentLoginhistory;
}
public void setCurrentLoginhistory(Loginhistory currentLoginhistory) {
this.currentLoginhistory = currentLoginhistory;
}
#In
private LoginhistoryService LoginhistoryService;
private static final long serialVersionUID = 8282995226262125676L;
public String create() {
currentLoginhistory.setRef("Test");
Integer id = LoginhistoryService.saveOrUpdate(this.currentLoginhistory);
return "/secure/userhome.xhtml";
}
#Override
public String initCurrentLoginhistory() {
currentLoginhistory = new Loginhistory();
return "/secure/common/history/loginHistory.xhtml";
}
}
Service interface:
#Local
public interface LoginhistoryService extends Serializable {
public abstract Integer saveOrUpdate(Loginhistory Loginhistory);
}
ServiceImpl class:
#Name("LoginhistoryService")
#Stateless
#AutoCreate
public class LoginhistoryServiceImpl implements LoginhistoryService {
private static final long serialVersionUID = 1L;
#In
private LoginhistoryDAO loginhistoryDAO;
public LoginhistoryServiceImpl() {
super();
}
#Override
// TODO what to do with lastmodified if it is modify
public Integer saveOrUpdate(Loginhistory loginhistory) {
LoginhistoryEntity loginhistoryEntity = LoginhistoryMapper.mapLoginhistoryEntity(loginhistory);
Integer loginhistoryId = loginhistoryDAO.saveOrUpdate(loginhistoryEntity);
return loginhistoryId;
}
}
Mapper class:
public class LoginhistoryMapper {
public static LoginhistoryEntity mapLoginhistoryEntity(
Loginhistory loginhistory) {
LoginhistoryEntity loginhistoryEntity = new LoginhistoryEntity();
loginhistoryEntity.setId(loginhistory.getId());
loginhistoryEntity.setName(loginhistory.getName());
loginhistoryEntity.setDate(loginhistory.getDate());
return loginhistoryEntity;
}
}
DAO interface:
#Local
public interface LoginhistoryDAO extends Serializable {
public Integer saveOrUpdate(LoginhistoryEntity newLoginhistory);
}
JPAclassDAOImpl class:
#Name("loginhistoryDAO")
#Stateless
#AutoCreate
public class JPALoginhistoryDaoImpl implements LoginhistoryDAO {
private static final long serialVersionUID = -6173881454668735683L;
#PersistenceContext(unitName = "clrp")
private EntityManager entityManager;
Logger logger = Logger.getLogger(this.getClass());
public void setEntityManager(EntityManager em) {
this.entityManager = em;
}
#Override
public Integer saveOrUpdate(LoginhistoryEntity newLoginhistory) {
entityManager.merge(newLoginhistory);
return newLoginhistory.getId();
}
}
My entity is as follows:
#Entity
#Table(name="loginhistory")
#NamedQueries(value = {
#NamedQuery(name = LoginhistoryEntity.fetchAll, query = "FROM LoginhistoryEntity" )})
public class LoginhistoryEntity implements Serializable {
private static final long serialVersionUID = 1L;
public final static String fetchAll = "LoginhistoryEntity.fetchAll";
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false)
private int id;
#Column(name = "Date")
private Date date;
#Column(name = "Name")
private String name;
#Column(name = "Ref")
private String ref;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
public void setRef(String ref) {
this.ref = ref;
}
public String getRef() {
return ref;
}
}
Finally I found the mistake, trivial one and sorry for your time here..
My entity was previously
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "historyId", updatable = false)
private Integer historyId;
Problem here the integer type, it should be
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false)
private Integer id;
Cheers