Reputation: 734
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?
Upvotes: 9
Views: 5637
Reputation: 16400
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
Upvotes: 6
Reputation: 140
@GeneratedValue(strategy = GenerationType.IDENTITY)
while persisting you can use entitymanager.merge() which will do the same functionality which you want.
Hope this will work!
Upvotes: -1