当id(primay keys)大于1时,如何获取EntityManager.getReference?

时间:2016-01-05 02:55:57

标签: java jpa entitymanager zk

伙计们,我拼命地知道如何将EntityManager.getReference与多于一个主键一起使用,因为当我想要更新数据时总是会出错, 错误消息类似:

  

[EL Fine]:sql:Connection(1713950866) - SELECT Category,SubCategory,Code,CreatedBy,CreatedDateTime,IsActive,Remarks,UpdatedBy,UpdatedDateTime,Value FROM master.sysParameter WHERE(((Category =?)AND( SubCategory =?))AND(Code =?))        bind => [acm,acm,acm]   javax.persistence.EntityNotFoundException:找不到id:acm的实体       在org.eclipse.persistence.internal.jpa.EntityManagerImpl.getReference(EntityManagerImpl.java:1398)

在我的代码中我想定义3个变量,但我只得到1(acm)。 这是我的代码示例:

    public boolean updateSysParameter(MasterSysParameterEntity masterSysParameter) {
    // TODO Auto-generated method stub
    boolean retVal = false;
    try{
        MasterSysParameterEntity updateSysParameter;
        em = getEntityManagerFactory();
        em.getTransaction().begin();
        System.out.println("masterSysParameter.getCategory() => " +masterSysParameter.getCategory());

        updateSysParameter = em.getReference(MasterSysParameterEntity.class, masterSysParameter.getCategory());
        updateSysParameter = em.getReference(MasterSysParameterEntity.class, masterSysParameter.getSubCategory());
        updateSysParameter = em.getReference(MasterSysParameterEntity.class, masterSysParameter.getCode());

        updateSysParameter = em.merge(masterSysParameter);

        em.getTransaction().commit();
        retVal = true;
    }catch (Exception e) {
        if(em != null && null != em.getTransaction())
            em.getTransaction().rollback();
        e.printStackTrace();
    } finally {
        if (em != null) {
            em.close();
        }
    }
    return retVal;
}

非常感谢任何建议和帮助,这真的意味着很多

1 个答案:

答案 0 :(得分:2)

如果实体中有多个@Id字段,那么您可以定义@IdClass on the entity for the composite id。所以你调用em.getReference传递第二个参数作为" IdClass"的实例。

MyIdClass myId = new MyIdClass(...); // Pass in whatever args your IdClass needs
MyEntity ent = em.getReference(MyEntity.class, myId);