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

bee*_*tri 4 jpa lob detach datanucleus

实体类:

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;
....
Run Code Online (Sandbox Code Playgroud)

持久性类/逻辑:

 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;
}
Run Code Online (Sandbox Code Playgroud)

消费者类/逻辑:

   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);
    }
Run Code Online (Sandbox Code Playgroud)

错误我得到:

引起:javax.jdo.JDODetachedFieldAccessException:您刚刚尝试访问字段"attachment"但是在分离对象时此字段未分离.要么不访问此字段,要么在分离对象时将其分离.在com.ge.dsp.iwork.test上的com.ge.dsp.iwork.entity.CustomerSurvey.jdoGetattachment(CustomerSurvey.java)com.ge.dsp.iwork.entity.CustomerSurvey.getAttachment(CustomerSurvey.java:89) .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)在org的java.lang.reflect.Method.invoke(Method.java:597).

谢谢,

Zaw*_* oo 7

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

  1. 默认加载 @Log属性将是FetchType.LAZY.
  2. Persistence Context会后明确clear()的过程EntityManager.这意味着所有托管实体都将成为分离状态.更多信息在这里.
  3. 当一个 Entity处于分离状态时,如果您访问提取值,您将在提到时遇到问题.

简答:

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

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

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