0

Can the following id generation be implemented without depending on Hibernate @GenericGenerator, with pure JPA only?

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;

@Entity
public class MyObject implements Serializable {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "my.IdGenerator")
    @Column(name = "ID", length = 36, nullable = false)
    private String id;

    // ...
}
yglodt
  • 13,807
  • 14
  • 91
  • 127

2 Answers2

1

You can use a @PrePersist callback

@Id
@Column(name = "ID", length = 36, nullable = false)
private String id;

// ...

@PrePersist
public void prePersist() {
   id = UUID.randomUUID(); 
} 

More on Life Cycle callbacks here: Configuring a Life Cycle Callback Method on a JPA Entity

gustf
  • 1,959
  • 13
  • 20
0

There are a few JPA methods for doing this (meaning it could be implemented by EclipseLink, Hibernate, or somet other JPA implemntation)

Here's how you'd do it if you had a sequence object:

@Id
@javax.persistence.SequenceGenerator( name = "mySequence", sequenceName = "MY_TABLE_SEQ", allocationSize = 1, initialValue = 1 )
@javax.persistence.GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "mySequence" )
@Column( name = "MY_TABLE_ID" )
private Integer myTableId;

And here's how if it were an identity column:

@Id
@javax.persistence.GeneratedValue( strategy = GenerationType.IDENTITY )
@Column( name = "MY_TABLE_SEQ" )
private Long myTableId;

Again, the thing to note here is that this is pure JPA, not Hibernate-specific.

Dean Clark
  • 3,770
  • 1
  • 11
  • 26