In my Java EE application that runs on GlassFish 4.1 with Derby 10.11.1.1, I am currently using the following technique to auto generate my primary keys in each of my jpa Entities:
@TableGenerator(name = "Entity1_Generator", table = "ID_Gen", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VAL", initialValue = 0, allocationSize = 1)
@Id
@GeneratedValue(generator = "Entity1_Generator")
private Long id;
I decided yesterday that it would be nice to move the @Id
to a @MappedSuperclass
and then Extend the mapped superclass in each of my entities. Unfortunately, I discovered quickly that EclipseLink does not support overriding the @TableGenerator
or @SequenceGenerator
on subclasses. The following are a few references:
- MappedSuperclass - Change SequenceGenerator in Subclass
- Why does eclipselink 2.5.0 does not support Override TableGenerator or SequenceGenerator in subclasses while hiberate does support?
Based on this information, I came up with the following options:
- Abandon my goal of moving the
@Id
to my mapped superclass. (Boo!) - Use a single
@TableGenerator
for all my entities. (Yuk!) - Create a custom generator by extending the EclipseLink Sequence object.
- Abandon
@GeneratedValue
and create the primary keys using an EJB.
I review the following EclipseLink Custom Sequencing information but wasn't sure from the documentation that I would be able to grab distinguishing information that would allow me to create a sequence for each entity.
I am now thinking that it would be easy to create an stateless or singleton EJB that would control my sequences. I would simply remove the @GeneratedValue
annotation from my code and perform the following code before persisting my entity.
myEntity.setId(idGenerator.getNextMyEntityId());
Using the IDGenerator to control my primary key generation, would have the following advantages:
- Move
@Id
to mapped superclass. - Remove
@TableGenerator
from each entity. - Complete control over how sequences are generated.
What are the risks associated with using an EJB to create my Primary Keys?