Bima Ardi
Bima Ardi

Reputation: 81

How can I get EntityManager.getReference when the id(primay keys) are more than 1?

guys, I desperately to know how can I use EntityManager.getReference with more than 1 primary keys because I always get error when I want to update data, the error message kind of like :

[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: Could not find entity for id: acm at org.eclipse.persistence.internal.jpa.EntityManagerImpl.getReference(EntityManagerImpl.java:1398)

which in my codes I want to define 3 variables but I only get 1 (acm). here's the examples of my codes :

    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;
}

Thanks a lot for any advice and help, it really means a lot

Upvotes: 1

Views: 1564

Answers (1)

Neil Stockton
Neil Stockton

Reputation: 11531

When you have multiple @Id fields in an entity then you define an @IdClass on the entity for the composite id. And so you call em.getReference passing in the second argument as an instance of the "IdClass".

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

Upvotes: 3

Related Questions