Markus G. Markus G. - 4 months ago 30
Java Question

JPA @GeneratedValue and @Id

In my Entity there's a field called id, marked with the annoation @Id (which I set manually) and know I wanted to know, is there a possibility to auto generate a Unique Id (with @GeneratedValue) but I also want to set the ID manually and when not set it should generate it auotmatically.


private long id;

creation of the entity

new Entity(someid) //Once with ID and no generated value
new Entity() //Second without ID and generated unique value

I hope you can understand me.


Well I don't think that this would work. JPA automatically generates your id value and is responsible for the @GeneratedValue. Ask yourself 'what happens if there is already an existing entity with the id 100. And I create manually a new entity with tne id 100'. Intuitively I would say that JPA (or the implementation) throws an expection.

While writing the above answer I got the idea of writing your own generator (not tried at all, just coded down here at stackoverflow.

You can pass your own implementation of a generator to the @GeneratedValue annotation

@GeneratedValue(startegy = GenerationType.IDENTITY, generator="generatedIdOrCustomId")
@GenericGenerator(name="generatedIdOrCustomId", strategy="GeneratedIdOrCustomId")
private Long id;

And the custom implementation should look like this:

public class GeneratedIdOrCustomId extends IdentityGenerator {

public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
    if (((YourEntity) obj).getId() == null) {
        // the id is null, let JPA create an id.
        return super.generate(session, obj);
    } else {
        // the id is set and should not be generated by JPA.
        return ((YourEntity) obj).getId();

The generate method is just a quick and dirty implementation. You'll have to check for example also if the obj == null and throw a (Hibernate)Exception in this case.