jakartaee / persistence

https://jakartaee.github.io/persistence/
Other
191 stars 55 forks source link

"entity local" @SequenceGenerator/@TableGenerator #406

Closed gavinking closed 12 months ago

gavinking commented 1 year ago

The spec says that a @SequenceGenerator and @TableGenerator annotation defines a named generator whose name is global to the whole persistence unit.

But a very common idiom is to specify one of these annotations directly on the @Id attribute or @Entity class, and in that case it makes much more sense for the generator to be seen as local to the entity.

I'm not completely sure how we should "fix" this, but one idea would be to make the name annotation member optional, and treat @SequenceGenerator and @TableGenerator annotations without a name as local to the entity, and used by default. For example:

@Entity 
class Book {
    @Id @GeneratedValue
    @SequenceGenerator(sequenceName="seq_book", allocationSize=10)
    Long id;
}

Or:

@SequenceGenerator(sequenceName="seq_book", allocationSize=10)
@Entity 
class Book {
    @Id @GeneratedValue
    Long id;
}

would now be accepted, and the @SequenceGenerator would be visible only to the Book entity, and implicitly used as the generator for that entity.

This would avoid the need for nastiness like:

@Entity 
class Book {
    @Id @GeneratedValue(strategy=SEQUENCE, generator="bookSeq")
    @SequenceGenerator(name="bookSeq", sequenceName="seq_book", allocationSize=10)
    Long id;
}

and is more typesafe to boot (one less stringly-typed name).