![](/img/trans.png)
[英]Hibernate org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:
[英]org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection
我從jsp url: "ProductByName"
調用自動完成功能。 在控制台中響應時顯示
POST http://localhost:8082/Store/SingleProduct 500 (Internal Server Error)
在jsp中
$(".name").autocomplete({
source: function(request, response) {
$.ajax({
url: "ProductByName",
dataType: "json",
data: {
str: request.term,
maxRows: 5
},...
在struts.xml
<action name="ProductByName" class="iland.productdetails.ProductDetailsAction" method="fetchByProductName">
<result type="json">
<param name="includeProperties">productList\[\d+\]\.id,
productList\[\d+\]\.name,
productList\[\d+\]\.description
</param>
<param name="excludeNullProperties">true</param>
</result>
</action>
我只想獲取productList
幾個屬性
行動課
public class ProductDetailsAction extends ActionSupport {
private long id;
private String barCode;//bardoce
private String name;
private String desc;
private long quantity;
private float unitPrice;
private float sellingPrice;
private float totalSellingPrice;
private long clientId;
private ArrayList<BillDetails> BillList;
private Date startDate;
private Date endDate;
private int discountPercentage;
private Timestamp addDate;
private String dataStatus;
private ArrayList<ProductDetailsAction> productList;
private ArrayList<Product> productBillList;
public String fetchByProductName() {
ProductDetailsBusiness pdb = new ProductDetailsBusiness();
Map data = pdb.fetchByProductName(getName());
setProductList((ArrayList) data.get("list"));
return SUCCESS;
}
//other methods and getter and setter
}
我正在關注異常
SEVERE: Exception occurred during processing request: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: iland.hbm.Client.billDetailses, no session or session was closed
org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: iland.hbm.Client.billDetailses, no session or session was closed
at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:246)
at org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:178)
at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:168)
at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:134)
at org.apache.struts2.json.JSONWriter.write(JSONWriter.java:102)
at org.apache.struts2.json.JSONUtil.serialize(JSONUtil.java:116)
at org.apache.struts2.json.JSONResult.createJSONString(JSONResult.java:197)
at org.apache.struts2.json.JSONResult.execute(JSONResult.java:171)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:161)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
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:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: iland.hbm.Client.billDetailses, no session or session was closed
at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:246)
at org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:178)
at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:168)
at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:134)
at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:390)
at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:231)
... 71 more
Caused by: org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: iland.hbm.Client.billDetailses, no session or session was closed
at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:246)
at org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:178)
at org.apache.struts2.json.JSONWriter.process(JSONWriter.java:168)
at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:134)
at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:390)
at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:231)
... 76 more
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: iland.hbm.Client.billDetailses, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:111)
at org.hibernate.collection.PersistentSet.equals(PersistentSet.java:429)
at java.util.Vector.indexOf(Vector.java:408)
at java.util.Vector.contains(Vector.java:367)
at org.apache.struts2.json.JSONWriter.value(JSONWriter.java:117)
at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:390)
at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:231)
... 81 more
編輯: fetchByProductName(getName());
方法僅包含Jdbc代碼。 那么為什么要使用休眠錯誤器呢?
我正在從數據庫中獲取日期,也正在控制台上打印。 在成功之前,我給了System.out.println(
In action );
這是正確的aslo打印它不必訪問數據庫中的數據,然后為什么failed to lazily initialize a collection of XXX
如何解決此問題。
編輯
public class ProductDetailsBusiness {
ProductDetailsAction pda = null;
PreparedStatement ps = null;
ResultSet rs = null, res = null;
Connection con = null;
String status = null;
ArrayList<ProductDetailsAction> ar = null;
public Map fetchByProductName(String name, long cid) {
System.out.println(" ProductBusiness fetchByProductName()");
status = "success";
System.out.println("Name is " + name);
ar = new ArrayList();
con = ConnectionFactory.getConnection();
try {
String query = "select * from product "
+ "where status=? and cid=? "
+ "order by add_date";
ps = con.prepareStatement(query);
ps.setString(1, "active");
ps.setLong(2, cid);
System.out.println("Before execution");
res = ps.executeQuery();
System.out.println("Details are");
while (res.next()) {
pda = new ProductDetailsAction();
long id1 = res.getLong("id");
String barCode = res.getString("barcode");
String name1 = res.getString("name");
String desc = res.getString("description");
long quntity = res.getLong("quntity");
float unit_price = res.getLong("unit_price");
float selling_price = res.getLong("selling_price");
int discount_percent = res.getInt("discount_percent");
pda.setId(id1);
pda.setBarCode(barCode);
pda.setName(name1);
pda.setDesc(desc);
pda.setQuantity(quntity);
pda.setUnitPrice(unit_price);
pda.setSellingPrice(selling_price);
pda.setDiscountPercentage(discount_percent);
System.out.println("id "+id1+" name "+name1+" "+desc);
ar.add(pda);
}
con.close();
} catch (SQLException s) {
status = "failure";
System.out.println("SQL code does not execute." + s);
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException sqe) {
status = "failure";
System.out.println("SQLException " + sqe);
}
}
Map m = new HashMap();
m.put("status", status);
m.put("list", ar);
return m;
}
//other methods
}
還更新了動作課程,請同時查看
LazyInitializationException
是此問題的根本原因,當Struts 2 json插件嘗試序列化productList
對象時,將引發此問題。 根據例外文件
(它)指示訪問會話上下文之外的未提取數據。 例如,當關閉會話后訪問未初始化的代理或集合時。
這意味着您正在嘗試訪問billDetailses
實體的集合, billDetailses
實體以數據庫中的Java休眠代理的形式加載。 根據休眠文件
如果在Session范圍之外訪問未初始化的集合或代理,即當擁有該集合或對該代理的引用的實體處於分離狀態時,Hibernate將拋出LazyInitializationException。
因此,這意味着未初始化billDetailses
list
集合,您可以在完成操作之前使用強制強制初始化
Hibernate.initialize(data) // collection entity
在集合映射上設置FetchType.EAGER
也可以解決該問題,但是它將每次添加到billDetailses
對象中,因為每次將此對象加載到Java中時,都會強制加載其集合,而從我的角度來看,這就像購買Ferrari並始終在第一時間運行齒輪。
如果您經常收到LazyInitializationException
我建議嘗試使用OpenSessionInViewFilter
,它可以使休眠會話從請求開始就保持打開狀態,直到從應用程序完成響應為止。
JSON的序列化過程由JSON結果控制,JSON結果是您在項目中使用的JSON插件的一部分。 而且您已經知道,要限制序列化程序使用的屬性,您應該使用json
結果的includeProperties
。 還有一個root
屬性,您應該檢查。 如果未指定,則json結果默認使用值堆棧的top
對象。 如果您的操作是模型驅動的,那么模型將覆蓋action 。 所以,你在使用的正則表達式includeProperties
應用於模型對象,串行這是JSONWriter
使用BeanInfo
提取bean的屬性。 首先,檢查這些屬性是否存在@JSON
批注,如果它具有serialize=false
,則將其跳過,否則將包括在內。 這樣,您就可以通過把注解,你不會序列化JSON等屬性控制序列化過程@OneToMany
性能等,然后includeProperties
或excludeProperties
如果他們不為空進行檢查。 此時,您應該確認,如果您沒有與指定模式匹配的屬性,那么它們將不會被序列化。 因此,讓我們轉到LazyInitializationException
,就像我說的那樣,如果模型層次結構中曾經有@JSON
注釋,則應在其中放置serialize=false
,因為默認情況下為true
。
@JSON(serialize=false)
public Object getBillDetailses(){ return billDetailses; }
您在操作類中說了productList
,那么您應該配置結果
<!-- Result config -->
<result type="json">
<param name="includeProperties">
^productList\[\d+\]\.id,
^productList\[\d+\]\.name,
^productList\[\d+\]\.description
</param>
<param name="root">
#action
</param>
</result>
注意, ^
代表表達式的開頭,因此僅包含動作屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.