JDODetachedFieldAccessException:您刚刚尝试访问字段"attachment"但在分离对象时未分离此字段



Entity class:

public class CustomerSurvey implements Serializable {
@Id @GeneratedValue(strategy=GenerationType.SEQUENCE, 
generator="CUSTOMER_SURVEY_SEQUENCE")
@Column(name = "SURVEYID", nullable = false)
private String surveyId;

@Column(name="ATTACHMENT")
@Lob
private byte[] attachment;
....

持久性类/逻辑:

public List<CustomerSurvey> getSurveysByCustomer(String custNo)
throws WorkServiceException {
EntityManager em = entityManagerFactory.createEntityManager();
Query query = em.createNamedQuery("customerSurvey.findByCustomer")
.setParameter("custNo", custNo);
logger.debug(query);
List<CustomerSurvey> surveys = query.getResultList();
em.clear();
em.close();
return surveys;
}

消费者类/逻辑:

List<CustomerSurvey> reviewSurveys = workService.getSurveysByCustomer("testCNo2");
for(CustomerSurvey rsurvey: reviewSurveys) {
Object obj = rsurvey.getAttachment();
byte[] buffer = (byte[]) obj;
OutputStream out = new FileOutputStream("C:\Temp\TulipsOut.jpg");
out.write(buffer);
}

我得到的错误是:

原因:javax.jdo.JDODetachedFieldAccessException:您刚刚尝试访问字段"附件",但在分离对象时未分离此字段。要么不访问此字段,要么在分离 obj 时分离它 等。 at com.ge.dsp.iwork.entity.CustomerSurvey.jdoGetattachment(CustomerSurvey.java) at com.ge.dsp.iwork.entity.CustomerSurvey.getAttachment(CustomerSurvey.java:89) at com.ge.dsp.iwork.test.WorkServiceTest.testSubmitSurveyResponse(WorkServiceTest.java:270) 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.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1581) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1522) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452) ...还有 14 个

谢谢

主要问题是private byte[] attachment;.

  1. @Log属性的默认加载将为FetchType.LAZY
  2. EntityManagerclear()过程后,Persistence Context会很清楚。这意味着所有托管实体都将变为分离状态。更多信息在这里。
  3. Entity处于分离状态时,如果您访问获取值,则会遇到您所提到的问题。

简答:

em.clear()处理后,将分离实体实例surveys。这就是为什么您无法检索attachment的值attachment因为延迟加载(FetchType.LAZY)。

解决方案:使用FetchType.EAGER。我认为,大多数人不建议使用急切加载。

@Column(name="ATTACHMENT")
@Basic(fetch = FetchType.EAGER)
@Lov
private byte[] attachment;

最新更新