Gal Sosin
Gal Sosin

Reputation: 734

How to generate ID only if it's null on persisting

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

Answers (2)

Christian Beikov
Christian Beikov

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

Birju B
Birju B

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

Related Questions