javaspringhibernatejpahibernate-entitymanager

EntityManager merge using specific column other than id


I'm currently using Spring and Hibernate framework, and have an entity with:

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID")
private Long id;

@Column(name="ACC_ID")
private Long accId;

Now, in a specific case I'd like to merge an object in the database using column "ACC_ID" instead of "ID", however, I do not want to assign @Id to accId because I do not want to change the entity itself.

Is there anything I can do on the merge function? (But apparently merge takes no other parameter than an object)

entityManager.merge(entityObject)

Thanks in advance for any clue or help. =)


Solution

  • entityManager.merge(entityObject) can be used if it is your primary key based.

    If it is another unique constraint you'd have to handle it by yourself. First try to find an entity with that value (with a query).
    If a match is found, copy the primary key to your new entity before saving as normal.

    For example:

    public Entity save(Entity entity, boolean rollback) {
        // look for a match, you'll have to implement your own method here
        Entity match = getEntityByValue("column_name", entity.getMergeColumn());
    
        if (match != null) {
            // copy the primary key
            entity.setId(match.getId());
        }
    
        // save the entity
        save(entity, rollback);
    }