Set ID manually with Hibernate in AUTO mode

Asked

Viewed 71 times

1

Hi, I was wondering if there is a possibility to set the ID manually when using Hibernate in auto increment mode.

I want it to use auto increment but in some specific situations I need to query the existing Ids in the database and set the ID manually.

But every time I try he ignores the ID I put on the entity and puts another.

1 answer

2


Yes, has how, so that it is possible to do the following (using this question as a reference):

Add this to your id attribute':

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY, generator="IdOrGenerated")
@GenericGenerator(name="IdOrGenerated",
              strategy="....UseIdOrGenerate"
)
@Column(name = "ID", nullable = false)
private Integer id;

And add this class:

import org.hibernate.id.IdentityGenerator;
...
public class UseIdOrGenerate extends IdentityGenerator {
private static final Logger log = Logger.getLogger(UseIdOrGenerate.class.getName());

@Override
public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
if (obj == null) throw new HibernateException(new NullPointerException()) ;

if ((((EntityWithId) obj).getId()) == null) {
    Serializable id = super.generate(session, obj) ;
    return id;
} else {
    return ((EntityWithId) obj).getId();

}
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.