Define ID manually with Hibernate in AUTO mode

1

Hello, I would like to know if there is a possibility to set the ID manually when using hibernate in auto increment mode.

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

But every time I try it ignores the ID I put in the entity and puts another.

    
asked by anonymous 22.07.2016 / 20:29

1 answer

2

Yes, you can do this by doing this (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();

}
}
    
22.07.2016 / 20:35