How Does the JPA @Sequencegenerator Annotation Work

What is sequenceName in @SequenceGenerator annotation and how does it work?

  1. You are only creating a new sequence if you are using Hibernate to create your schema. That is controlled by the hibernate.hbm2ddl.auto property or the javax.persistence.schema-generation family of properties.

  2. Yes

  3. It falls back to a default naming convention for the sequence.

If your table automatically generates the id, then you don't need to define the sequences directly. You can just use the annotation @GeneratedValue(strategy = GenerationType.IDENTITY). This not only reduces your code complexity, but also now each insert will take one query instead of two.

@SequenceGenerator on class annotated with @MappedSuperclass

Here is what the JPA 1.0 spec says about the SequenceGenerator annotation:

9.1.37 SequenceGenerator Annotation


The SequenceGenerator annotation
defines a primary key generator that
may be referenced by name when a
generator element is specified for the
GeneratedValue annotation. A
sequence generator may be specified
on the entity class or on the primary key field or property. The
scope of the generator name is global
to the persistence unit (across all
generator types).

And a mapped superclass is not an entity. So according to the way I read the spec, what you want to do is not possible. Either make the Intermed class an entity or put the SequenceGenerator on the sub classes.

JPA SequenceGenerator: All generators in single table

You need to use a Table generator (which stores the id value in a specified table) rather than Sequence generator (which uses native SQL sequences). This simplified example below should give you the idea, but you can control the schema for the table by specifying more attributes on the @TableGenerator annotation.

@TableGenerator(name="MyTableGen", table="SEQUENCES", pkColumnValue="MyClass")
@Entity
public class MyEntity
{
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="MyTableGen")
private long myId;

...
}

Hibernate JPA Sequence (non-Id)

Looking for answers to this problem, I stumbled upon this link

It seems that Hibernate/JPA isn't able to automatically create a value for your non-id-properties. The @GeneratedValue annotation is only used in conjunction with @Id to create auto-numbers.

The @GeneratedValue annotation just tells Hibernate that the database is generating this value itself.

The solution (or work-around) suggested in that forum is to create a separate entity with a generated Id, something like this:


@Entity
public class GeneralSequenceNumber {
@Id
@GeneratedValue(...)
private Long number;
}

@Entity
public class MyEntity {
@Id ..
private Long id;

@OneToOne(...)
private GeneralSequnceNumber myVal;
}


Related Topics



Leave a reply



Submit