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;
.
@Log
属性的默认加载将为FetchType.LAZY
。EntityManager
的clear()
过程后,Persistence Context
会很清楚。这意味着所有托管实体都将变为分离状态。更多信息在这里。- 当
Entity
处于分离状态时,如果您访问获取值,则会遇到您所提到的问题。
简答:
em.clear()
处理后,将分离实体实例surveys
。这就是为什么您无法检索attachment
的值attachment
因为延迟加载(FetchType.LAZY
)。
解决方案:使用FetchType.EAGER
。我认为,大多数人不建议使用急切加载。
@Column(name="ATTACHMENT")
@Basic(fetch = FetchType.EAGER)
@Lov
private byte[] attachment;