7

I have two different components that use two different DB's but the entity is on both DB's and I want it to have the same ID's always.

So basically when the ID is null I want it to be auto generated, if it's not null use the ID.

I'm using hibernate.

@Id
@Column(name = COLUMN_ID, unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
    return id;
}

Any suggestions?

Gal Sosin
  • 714
  • 7
  • 27
  • When the id is not null, it assume that this entity already present in DB and you should not use `EntityManager.persist(entity)` you should use `EntityManager.merge(entity)` – SternK Oct 07 '20 at 08:32
  • this question is quite unclear. You speak of entities in two databases and the ID needs to be "the same". What does that mean? If an entity is persisted, it needs to be saved in both databases at the same time using the same ID? – Gimby Oct 07 '20 at 13:27
  • First it will be saved on one DB (that will auto generate the ID) then it will be sent the entity already with an ID and it will save it with the same ID – Gal Sosin Oct 07 '20 at 15:00
  • @Sternk I want it keep the same ID – Gal Sosin Oct 07 '20 at 15:17

2 Answers2

6

You need a custom sequence generator for this:

public class SetableSequenceGenerator extends SequenceStyleGenerator {

    /**
     * Custom id generation. If id is set on the
     * com.curecomp.common.hibernate.api.Entity instance then use the set one,
     * if id is 'null' or '0' then generate one.
     */
    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object obj) {
        if ((obj != null) && (obj instanceof Entity)) {
            Entity<? extends Serializable> entity = (Entity<? extends Serializable>) obj;
            if ((entity.getId() == null) || (entity.getId().equals(0))) {
                return super.generate(session, obj);
            }
            return entity.getId();
        }
        return super.generate(session, obj);
    }
}

As strategy, you specify the FQN of the sequence generator class

Christian Beikov
  • 15,141
  • 2
  • 32
  • 58
-1

@GeneratedValue(strategy = GenerationType.IDENTITY)

while persisting you can use entitymanager.merge() which will do the same functionality which you want.

Hope this will work!

Birju B
  • 140
  • 1
  • 5