实体类:
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:您刚刚尝试访问字段“attachment”,但在分离对象时此字段未分离。要么不访问此字段,要么在分离obj时将其分离 等。 在com.ge.dsp.iwork.entity.CustomerSurvey.jdoGetattachment(CustomerSurvey.java) 在com.ge.dsp.iwork.entity.CustomerSurvey.getAttachment(CustomerSurvey.java:89) 在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) 在java.lang.reflect.Method.invoke(Method.java:597) 在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1581) 在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1522) 在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452) ......还有14个
谢谢,
答案 0 :(得分:7)
主要问题是private byte[] attachment;
。
@Log
属性的默认加载为FetchType.LAZY
。Persistence Context
clear()
进程后,EntityManager
将会清除。这意味着所有托管实体都将成为分离状态。更多信息是here。Entity
处于分离状态时,如果您访问提取值,则会在提及时遇到问题。 简答:
在em.clear()
进程之后,您的实体实例surveys
将被分离。这就是为什么,由于attachment
延迟加载(attachment
),您无法检索值FetchType.LAZY
。
解决方案:使用FetchType.EAGER
。我想,大多数人不建议使用急切加载。
@Column(name="ATTACHMENT")
@Basic(fetch = FetchType.EAGER)
@Lov
private byte[] attachment;