I have two piece of code segments, they are almost exactly the same, except their locations are different, one locates in RestLoginDLCtrl(a controller) the other locates in CouponManagerController(a controller).But one code segment is right, the other one throws org.hibernate.LazyInitializationException.
I know how to solve my problem. confused me the most is why one is OK the other is wrong, but they are almost the same code. why? Any help would be appreciate.
ConversionCode is a value object which has a set named codeRewards and managerService is a service class.
note:
Finally, I found some interesting phenomena. when I use ajax way to post the http request, two methods both well:
$.ajax({
type: "POST",
url: "/CouponInfo/useConversionCode.do",
data: {
code: key
},
dataType: "json",
success: function (data) {
}
});
But when I use form way, two methods both did not work:Does hibernate lazy initialize mechnism has relationship with http request way?
<form action=""></form>
The CouponManagerController controller class:
#Controller
#RequestMapping(value = "${adminPath}/CouponInfo")
public class CouponManagerController extends RestBaseCtrl {
#Autowired
CouponManagerService managerService;
#ResponseBody
public void useConversionCode(String code, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/json;charset=utf-8");
try {
LoginCustInfo info = (LoginCustInfo) request.getSession().getAttribute(SystemProperties.DUOLIJR_LOGIN_USER);
ConversionCode conversionCode = managerService.queryConversionCodeByCode(code);
if (conversionCode != null) {
managerService.useConversionCode(conversionCode, info.getCustId());
response.getWriter().print("[{\"success\":\"true\",\"message\":\"兑换成功\"}]");
} else {
response.getWriter().print("[{\"success\":\"false\",\"message\":\"无效兑换码\"}]");
}
} catch (ParseException e) {
e.printStackTrace();
try {
response.getWriter().print("[{\"success\":\"false\",\"message\":\"兑换失败!请稍后重试!\"}]");
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
try {
response.getWriter().print("[{\"success\":\"false\",\"message\":\"兑换失败!请稍后重试!\"}]");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
The RestLoginDLCtrl controller class:
#Controller
#RequestMapping(value = "${adminPath}/yqxqrest/loginDLCtrl", method = RequestMethod.POST)
public class RestLoginDLCtrl extends RestBaseCtrl {
#Autowired
CouponManagerService managerService;
#RequestMapping(value = "useConversionCode")
#ResponseBody
public void useConversionCode(String code, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/json;charset=utf-8");
try {
LoginCustInfo info = (LoginCustInfo) request.getSession().getAttribute(SystemProperties.DUOLIJR_LOGIN_USER);
ConversionCode conversionCode = managerService.queryConversionCodeByCode(code);
if (conversionCode != null) {
managerService.useConversionCode(conversionCode, info.getCustId());
response.getWriter().print("[{\"success\":\"true\",\"message\":\"兑换成功\"}]");
} else {
response.getWriter().print("[{\"success\":\"false\",\"message\":\"无效兑换码\"}]");
}
} catch (ParseException e) {
e.printStackTrace();
try {
response.getWriter().print("[{\"success\":\"false\",\"message\":\"兑换失败!请稍后重试!\"}]");
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
try {
response.getWriter().print("[{\"success\":\"false\",\"message\":\"兑换失败!请稍后重试!\"}]");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
The CouponManagerServiceImpl service class:
#Service("ActivitiesCouponsService")
public class CouponManagerServiceImpl extends BaseServiceImpl implements CouponManagerService {
#Autowired
JdbcDao jdbcDao;
#Autowired
ActivitiesCouponsService couponsService;
#Override
public ConversionCode queryConversionCodeByCode(String code){
ConversionCode conversionCode=null;
String hql = " from ConversionCode where DELETE_FLAG=0 and state=0 and code='"+code+"'";
List<ConversionCode> codes = jdbcDao.find(hql);
if (codes.size()>0) {
conversionCode=codes.get(0);
}
return conversionCode;
}
/**
* 使用兑换码
* #param conversionCode
* #param custId
* #throws ParseException
*/
#Override
public void useConversionCode(ConversionCode conversionCode,Integer custId) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date now = new Date();
Calendar endTime = Calendar.getInstance();
endTime.setTime(sdf.parse(sdf.format(now)));
Set<ConversionCodeReward> codeRewards=conversionCode.getCodeRewards();
StringBuffer sb=new StringBuffer();
String a="";
for(ConversionCodeReward codeReward:codeRewards) {
CustActivitiesInfo activitiesInfo = new CustActivitiesInfo();
activitiesInfo.setCustId(custId);
activitiesInfo.setCouponsType(codeReward.getCouponsType());
String couponsName=couponsService.findUcTypeDictionaryBycode("COUPONS_TYPE", codeReward.getCouponsType() + "").getItemName();
activitiesInfo.setCouponsName(couponsName);
activitiesInfo.setActivitiesAmount(codeReward.getActivitiesAmount());
endTime.add(Calendar.DAY_OF_YEAR, Integer.valueOf(codeReward.getValidPeriod()));
endTime.add(Calendar.SECOND, -1);
activitiesInfo.setStartDate(sdf.parse(sdf.format(now)));
activitiesInfo.setEndDate(endTime.getTime());
activitiesInfo.setTaskAction("兑换码");
activitiesInfo.setUseMeetAmount(codeReward.getUseMeetAmount());
activitiesInfo.setUsePlanType(codeReward.getUsePlanType());
activitiesInfo.setUsePlanPeriod(codeReward.getUsePlanPeriod());
activitiesInfo.setState(1);
jdbcDao.saveObject(activitiesInfo);
sb.append("1张"+codeReward.getCouponsName()+"、");
}
conversionCode.setState(1);
jdbcDao.updateObject(conversionCode);
}
}
The ConversionCode value object class:
#Entity
#Table(name = "conversion_code")
public class ConversionCode extends BaseEntity implements java.io.Serializable{
private int id;
private String code;
private Date endDate;
private int state;
private String remark;
private Set<ConversionCodeReward> codeRewards;
public ConversionCode(int id,String code,Date endDate,int state,String remark){
super();
this.id=id;
this.code=code;
this.endDate=endDate;
this.state=state;
this.remark=remark;
}
public ConversionCode(){
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#Column(name = "end_date")
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
#Column(name = "state")
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
#ManyToMany(fetch=FetchType.LAZY,mappedBy="codes")
public Set<ConversionCodeReward> getCodeRewards() {
return codeRewards;
}
public void setCodeRewards(Set<ConversionCodeReward> codeRewards) {
this.codeRewards = codeRewards;
}
#Column(name = "remark")
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
The ConversionCodeReward value object class:
#Entity
#Table(name = "conversion_code_reward")
public class ConversionCodeReward extends BaseEntity implements java.io.Serializable{
private Integer id;
private String couponsName;
private int couponsType;
private double activitiesAmount;
private int validPeriod;
private double useMeetAmount;
private String usePlanType;
private int usePlanPeriod;
private Set<ConversionCode> codes;
public ConversionCodeReward(Integer id,String couponsName,int couponsType,double activitiesAmount,
int validPeriod,double useMeetAmount,String usePlanType,int usePlanPeriod){
super();
this.id=id;
this.couponsName=couponsName;
this.couponsType=couponsType;
this.activitiesAmount=activitiesAmount;
this.validPeriod=validPeriod;
this.useMeetAmount=useMeetAmount;
this.usePlanType=usePlanType;
this.usePlanPeriod=usePlanPeriod;
}
public ConversionCodeReward(){
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "coupons_name")
public String getCouponsName() {
return couponsName;
}
public void setCouponsName(String couponsName) {
this.couponsName = couponsName;
}
#Column(name = "coupons_type")
public int getCouponsType() {
return couponsType;
}
public void setCouponsType(int couponsType) {
this.couponsType = couponsType;
}
#Column(name = "activities_amount")
public double getActivitiesAmount() {
return activitiesAmount;
}
public void setActivitiesAmount(double activitiesAmount) {
this.activitiesAmount = activitiesAmount;
}
#Column(name = "valid_period")
public int getValidPeriod() {
return validPeriod;
}
public void setValidPeriod(int validPeriod) {
this.validPeriod = validPeriod;
}
#Column(name = "use_meet_amount")
public double getUseMeetAmount() {
return useMeetAmount;
}
public void setUseMeetAmount(double useMeetAmount) {
this.useMeetAmount = useMeetAmount;
}
#Column(name = "use_planType")
public String getUsePlanType() {
return usePlanType;
}
public void setUsePlanType(String usePlanType) {
this.usePlanType = usePlanType;
}
#Column(name = "use_planPeriod")
public int getUsePlanPeriod() {
return usePlanPeriod;
}
public void setUsePlanPeriod(int usePlanPeriod) {
this.usePlanPeriod = usePlanPeriod;
}
#ManyToMany(cascade={CascadeType.MERGE,CascadeType.REFRESH},fetch=FetchType.LAZY)
#JoinTable(name = "code_and_reward",
joinColumns = { #JoinColumn(name = "reward_id") },
inverseJoinColumns = { #JoinColumn(name = "code_id") })
#Where(clause="DELETE_FLAG=0")
public Set<ConversionCode> getCodes() {
return codes;
}
public void setCodes(Set<ConversionCode> codes) {
this.codes = codes;
}
}
The stack trace of the exception:
2015-12-16 15:38:34,059 ERROR (org.hibernate.LazyInitializationException:19) - failed to lazily initialize a collection of role: com.yiqixiangqian.entity.ConversionCode.codeRewards, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.yiqixiangqian.entity.ConversionCode.codeRewards, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86)
at org.hibernate.collection.PersistentSet.iterator(PersistentSet.java:163)
at com.yqxqfront.coupon.service.impl.CouponManagerServiceImpl.useConversionCode(CouponManagerServiceImpl.java:152)
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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:80)
at com.yiqixiangqian.common.log.LogAspect.around(LogAspect.java:31)
at sun.reflect.GeneratedMethodAccessor255.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:65)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:51)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:51)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy119.useConversionCode(Unknown Source)
at com.yqxqfront.rest.controller.RestLoginDLCtrl.useConversionCode(RestLoginDLCtrl.java:665)
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:219)
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:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:155)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.channel.ChannelProcessingFilter.doFilter(ChannelProcessingFilter.java:144)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.yqxqfront.rest.filter.SessionFilter.doFilter(SessionFilter.java:186)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.yqxqfront.filter.ImageVerifyCodeFilter.doFilter(ImageVerifyCodeFilter.java:66)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
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:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:615)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:617)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1774)
at java.lang.Thread.run(Thread.java:662)
Hibernate: select custmessag0_.UID as UID245_, custmessag0_.CREATE_DATE as CREATE2_245_, custmessag0_.CREATED_BY as CREATED3_245_, custmessag0_.DELETE_FLAG as DELETE4_245_, custmessag0_.LAST_UPDATE_DATE as LAST5_245_, custmessag0_.UPDATE_BY as UPDATE6_245_, custmessag0_.VERSION as VERSION245_, custmessag0_.CONTENT as CONTENT245_, custmessag0_.CUST_ID as CUST9_245_, custmessag0_.ISCHECK as ISCHECK245_, custmessag0_.PUB_DATE as PUB11_245_, custmessag0_.TITLE as TITLE245_, custmessag0_.TYPE as TYPE245_ from cust_message custmessag0_ where custmessag0_.CUST_ID=? and custmessag0_.ISCHECK=? and custmessag0_.DELETE_FLAG=0
failed to lazily initialize a collection of role: com.yiqixiangqian.entity.ConversionCode.codeRewards, no session or session was closed
The useConversionCode() method which locates in CouponManagerController controller is OK:
The useConversionCode() method which locates in RestLoginDLCtrl controller is wrong and throws a LazyInitializationException exception:
Finally, I found some interesting phenomena. when I use ajax way to post the http request, two methods both well:
$.ajax({
type: "POST",
url: "/CouponInfo/useConversionCode.do",
data: {
code: key
},
dataType: "json",
success: function (data) {
}
});
but when I use form way, two methods both did not work:
<form action=""></form>
Does hibernate lazy initialize mechnism has relationship with http request way?
I know how this issue occured.Suddenly, I found there is a OpenSessionInViewFilter in the web.xml file.
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
In my form post request way, I did not add the .do request suffix, so the OpenSessionInViewFilter did not work, so the LazyInitializationException occured.
But the ajax post request way added the .do request suffix, so the OpenSessionInViewFilter worked and LazyInitializationException did not occur.
Related
I'm following some tutorials on Hibernate and at a certain point i need to add a new attribute to a class called Produto. It should be no problem since I've done it before and had no issues, but the thing is that when I restart the server, the framework seems to be missing the added field and doesn't add it to the database table, therefore I get erros when I'm trying to use the attribute on my JSP.
the Class:
#Entity
public class Produto {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotEmpty
private String nome;
#NotEmpty
private String linkDaFoto;
#NotEmpty
#Column(columnDefinition="TEXT")
private String descricao;
#Min(20)
private double preco;
#ManyToMany
private List<Categoria> categorias = new ArrayList<>();
#Version
private int versao;
public int getVersao() {
return versao;
}
public void setVersao(int versao) {
this.versao = versao;
}
public List<Categoria> getCategorias() {
return categorias;
}
public void setCategorias(List<Categoria> categorias) {
this.categorias = categorias;
}
#Valid
#ManyToOne
private Loja loja;
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
//método auxiliar para associar categorias com o produto
//se funcionar apos ter definido o relacionamento entre produto e categoria
public void adicionarCategorias(Categoria... categorias) {
for (Categoria categoria : categorias) {
this.categorias.add(categoria);
}
}
public String getLinkDaFoto() {
return linkDaFoto;
}
public double getPreco() {
return preco;
}
public void setPreco(double preco) {
this.preco = preco;
}
public void setLinkDaFoto(String linkDaFoto) {
this.linkDaFoto = linkDaFoto;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public void setLoja(Loja loja) {
this.loja = loja;
}
public Loja getLoja() {
return loja;
}
}
The Error:
org.apache.jasper.JasperException: javax.el.PropertyNotFoundException: Property [versao] not found on type [br.com.caelum.model.Produto]
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:638)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:514)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:168)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1244)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1027)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
javax.el.PropertyNotFoundException: Property [versao] not found on type [br.com.caelum.model.Produto]
javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:260)
javax.el.BeanELResolver$BeanProperties.access$300(BeanELResolver.java:212)
javax.el.BeanELResolver.property(BeanELResolver.java:347)
javax.el.BeanELResolver.getValue(BeanELResolver.java:92)
org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:113)
org.apache.el.parser.AstValue.getValue(AstValue.java:169)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:190)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:702)
org.apache.jsp.WEB_002dINF.views.produto.form_jsp._jspService(form_jsp.java:379)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:168)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1244)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1027)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Add hibernate.hbm2ddl.auto=update to your property file and restart the application. Hibernate should create the column for you automatically.
I think you must to clean the server from loaded data. Before a few weeks I have the same problem and when I cleaned the resources the problem was solved.
In my Spring Boot application, I am using JWT and a custom UserDetailsService. My AuthenticationManager is configured in a class annotated with #Configuration using the following method:
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception {
auth
.userDetailsService(userDetailsService)
.and()
.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(passwordEncoder());
}
Even though I specified a UserDetailsService, I am faced with the following problem: When my JWTLoginFilter intercepts the login request, and getAuthenticationManager().authenticate(token)
is called, I get the following exception:
org.springframework.security.authentication.InternalAuthenticationServiceException: PreparedStatementCallback; bad SQL grammar [select username,password,enabled from users where username = ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'butler-test.users' doesn't exist
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:126)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.kehrbusch.butler.apigate.jwt.JWTLoginFilter.attemptAuthentication(JWTLoginFilter.java:35)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
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:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
Caused by: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [select username,password,enabled from users where username = ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'butler-test.users' doesn't exist
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:684)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:716)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:726)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:776)
at org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl.loadUsersByUsername(JdbcDaoImpl.java:217)
at org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl.loadUserByUsername(JdbcDaoImpl.java:174)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
... 53 common frames omitted
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'butler-test.users' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:942)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1962)
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:692)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
... 60 common frames omitted
Setting a query using usersByUsernameQuery(query) on my AuthenticationManagerBuilder solves this problem, but is this the only solution? Shouldn't the UserDetailsService provide the information needed to retrieve the UserDetails for a username?
In case it helps, here is a snippet from the JWTLoginFilter:
#Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
AccountCredentials credentials = new ObjectMapper().readValue(httpServletRequest.getInputStream(), AccountCredentials.class);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
return getAuthenticationManager().authenticate(token);
}
This is my user entity (there are subclasses for specific users):
#Entity
#Table(name = "u_userdetails")
#Inheritance(strategy = InheritanceType.JOINED)
public class BasicUser implements UserDetails {
/**
*
*/
private static final long serialVersionUID = -109962402457721028L;
#Id
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "uuid2")
#Column(name = "id", columnDefinition = "BINARY(16)")
private UUID id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
public boolean isLocked() {
return locked;
}
#JsonDeserialize(using=LocalDateDeserializer.class)
#JsonSerialize(using=LocalDateSerializer.class)
#Column(name = "registration_date")
private LocalDate registrationDate;
#Column(name = "locked")
private boolean locked;
#Column(name = "enabled")
private boolean enabled;
#Column(name = "activation_key")
private String activationKey;
#Column(name = "email")
private String email;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(
name = "u_user_group",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "group_id", referencedColumnName = "id")
)
private List<Group> groups;
#ElementCollection
#CollectionTable(name="u_user_role", joinColumns=#JoinColumn(name="id"))
#Column(name="role")
private List<String> roles;
protected BasicUser() {}
public BasicUser(
#JsonProperty("id") UUID id,
#JsonProperty("username") String username,
#JsonProperty("password") String password,
#JsonProperty("registrationDate") LocalDate registrationDate,
#JsonProperty("locked") boolean locked,
#JsonProperty("enabled") boolean enabled,
#JsonProperty("activationKey") String activationKey,
#JsonProperty("email") String email,
#JsonProperty("roles") List<String> roles) {
this.id = id;
this.username = username;
this.password = password;
this.registrationDate = registrationDate;
this.locked = locked;
this.enabled = enabled;
this.activationKey = activationKey;
this.email = email;
this.roles = roles;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public static List<GrantedAuthority> getAuthorities(List<String> roles) {
List<GrantedAuthority> res = new ArrayList<>();
for(String role : roles) {
res.add(new BasicGrantedAuthority(role));
}
return res;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return username;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return !locked;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return enabled;
}
public LocalDate getRegistrationDate() {
return registrationDate;
}
public UUID getId() {
return id;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getAuthorities(roles);
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
}
Your configuration is wrong. You defined 2 authentication mechanisms, one is a user details service, and the second is a JDBC authentication.
In order to authenticate a user you only need one kind of mechanism to do that.
Your JVM "complains" about a bad SQL grammar, and if you'll examine the exception more closely you'll see that in particular JVM "complains" that he can't find the users table in your DB.
It seems that your JDBC authentication kicks in and tries to find the user credentials in the users DB table.
When you use this kind of authentication (JDBC) that is where and how Spring will try to authenticate the users, by trying to find a matching record within the users table in your DB.
You obviously mixing 2 authentications mechanisms by trying to read from:
#Table(name = "u_userdetails")
If you want to use JDBC authentication make sure to read the credentials from users table.
And not from:
#Table(name = "u_userdetails")
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 have two tables and on one of which I want to perform cascade on delete operation. I have tried using annotations both on the variable and on the getter method as well, but the variable one gives me this error:
An error occured
org.hibernate.exception.DataException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:102)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at no.nhst.user.dao.hibernate.IPUserDAOImpl.saveOrUpdate(IPUserDAOImpl.java:78)
at no.nhst.user.service.IPUserServiceImpl.saveOrUpdateIPUser(IPUserServiceImpl.java:103)
at no.nhst.user.web.admin.IPCustomerController.submitIpUsers(IPCustomerController.java:97)
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.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
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:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
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:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
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:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.sql.BatchUpdateException: Data truncation: Out of range value adjusted for column 'user_account' at row 1
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2028)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1451)
at org.apache.tomcat.dbcp.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297)
at org.apache.tomcat.dbcp.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 79 more
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Out of range value adjusted for column 'user_account' at row 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3607)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2427)
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1980)
... 84 more
Which is out of question because the column its referring to has BIGINT(10) size.
And, when I try using many to one annotation on getter method its not doing anything at all.
Here is my parent entity class:
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import no.nhst.user.model.resolver.AuthoritiesResolver;
import no.nhst.user.model.resolver.DefaultAuthoritiesResolver;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
#Entity
#Table(name = "ac_useraccount", uniqueConstraints = { #UniqueConstraint(columnNames = { "domain", "username" }) })
public class UserAccount extends BaseEntity implements UserDetails {
private static final long serialVersionUID = 1L;
private static final Log logger = LogFactory.getLog(UserAccount.class);
private String domain;
private String username;
private String password;
private String email;
private UserProfile userProfile;
private Date created;
private Date lastlogin;
private Date expires;
private Date credentialsExpires;
private boolean enabled = false;
private boolean locked = false;
private Set<Role> roles;
private Set<Group> groups;
private Set<UserApplication> applications;
private Set<Tag> tags = new HashSet<Tag>(); // optional "tags" to categorize a user in some way (not required)
private int maxSessions;
private AuthoritiesResolver authoritiesResolver;
UserAccount() {
this.applications = new HashSet<UserApplication>();
this.authoritiesResolver = new DefaultAuthoritiesResolver();
}
UserAccount(String domain, String username) {
this(domain, username, null, null, false);
}
UserAccount(String domain, String username, String password, String email, boolean enabled) {
this();
this.domain = domain;
this.username = username;
this.password = password;
this.email = email;
this.enabled = enabled;
}
public void setDomain(String domain) {
this.domain = domain;
}
public void setUserProfile(UserProfile userProfile) {
this.userProfile = userProfile;
if (null != userProfile)
userProfile.setUserAccount(this);
}
/** See http://docs.jboss.org/hibernate/core/3.5/reference/en-US/html/objectstate.html#objectstate-transitive */
// TODO: See AVIS-589 (update: that Jira issue is resolved)
#OneToOne(orphanRemoval=false,fetch = FetchType.LAZY)
#Cascade({CascadeType.ALL})
public UserProfile getUserProfile() {
return userProfile;
}
// TODO: AVIS-607, set to FetchType.EAGER temporarily
#OneToMany(mappedBy="userAccount", fetch=FetchType.LAZY)
#Cascade({CascadeType.ALL})
public Set<UserApplication> getApplications() {
return this.applications;
}
public void setApplications(Set<UserApplication> applications) {
this.applications = applications;
}
#OneToMany(mappedBy = "userAccount")
#Cascade({CascadeType.ALL})
public Set<Tag> getTags() {
return tags;
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
#Basic
public int getMaxSessions() {
return maxSessions;
}
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
}
#Temporal(TemporalType.TIMESTAMP)
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
#Temporal(TemporalType.TIMESTAMP)
public Date getLastlogin() {
return lastlogin;
}
public void setLastlogin(Date lastlogin) {
this.lastlogin = lastlogin;
}
// Transient (dependent on other fields) Spring Security UserDetails methods
#Transient
public Set<GrantedAuthority> getAuthorities() {
return authoritiesResolver.resolveAuthorities(this);
}
#Transient
public boolean isAccountNonExpired() {
boolean accountNonExpired = true;
if(this.expires != null) {
Date now = new Date();
if(now.after(expires)) {
accountNonExpired = false;
}
}
return accountNonExpired;
}
#Transient
public boolean isCredentialsNonExpired() {
boolean credentialsNonExpired = true;
if(this.credentialsExpires != null) {
Date now = new Date();
if(now.after(credentialsExpires)) {
credentialsNonExpired = false;
}
}
return credentialsNonExpired;
}
#Transient
public boolean isAccountNonLocked() {
return !this.locked;
}
public void setAccountNonLocked(boolean accountNonLocked) {
this.locked = !accountNonLocked;
}
public void setAuthoritiesResolver(AuthoritiesResolver authoritiesResolver) {
this.authoritiesResolver = authoritiesResolver;
}
#Transient
public AuthoritiesResolver getAuthoritiesResolver() {
return authoritiesResolver;
}
#Transient
public void addRole(Role role) {
this.getRoles().add(role);
role.getUserAccounts().add(this);
}
#Transient
public void removeRole(Role role) {
this.getRoles().remove(role);
role.getUserAccounts().remove(this);
}
#Transient
public void addGroup(Group group) {
this.getGroups().add(group);
group.getUserAccounts().add(this);
}
}
And here is my child class where I have used many to one annotation:
import org.hibernate.annotations.*;
import javax.persistence.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name="ac_ua_ip")
public class IPUser extends BaseEntity{
private static final long serialVersionUID = 1L;
private String ip;
private String comment;
private UserAccount userAccount;
public IPUser(){
}
public IPUser (String ip, String comment, UserAccount userAccount){
this.ip = ip;
this.comment = comment;
this.setUserAccount(userAccount);
}
#Column (nullable = false)
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
#Column
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
#ManyToOne(cascade = CascadeType.REMOVE)
public UserAccount getUserAccount() {
return userAccount;
}
public void setUserAccount(UserAccount userAccount) {
this.userAccount = userAccount;
}
}
And, I have removed lot of methods from parent class here just to have a clarity.
Any suggestions as to what I am doing wrong?
You will have to manage that problem manually, as it really does NOT make sense to cascade the remove operations from a ManyToOne relationship (otherwise your DB will not be consistent, as there could remain some IPUser entities without UserAccount).
See this answer for an excerpt from the JPA specification + a similar problem.
Alright, here's how I made it work.
I hope it goes all ok with the etiquette of answering self-asked-questions.
I added a reference to IPUser class in UserAccount class and it worked smoothly now. Here is the snippet I added:
private List<IPUser> ipUserList;
#OneToMany(mappedBy = "userAccount", fetch = FetchType.LAZY)
#Cascade({CascadeType.DELETE})
public List<IPUser> getIpUserList() {
return ipUserList;
}
public void setIpUserList(List<IPUser> ipUserList) {
this.ipUserList = ipUserList;
}
Please feel free to update my answer or ask any question regarding this.