Hibernate Primary Key Generator Annotation

Posted on by
Hibernate Primary Key Generator Annotation Rating: 4,5/5 3391 votes
  1. A composite primary key must either be represented and mapped as an embeddable class (see Section 9.1.14, “EmbeddedId Annotation”) or must be represented and mapped to multiple fields or properties of the entity class (see Section 9.1.15, “IdClass Annotation”). If the composite primary key class is mapped to multiple fields.
  2. The JPA specification supports 4 different primary key generation strategies which generate the primary key values programmatically or use database features, like auto-incremented columns or sequences. The only thing you have to do is to add the @GeneratedValue annotation to your primary key attribute and choose a generation strategy.
  3. JPA and Hibernate require you to specify at least one primary key attribute for each entity. You can do that by annotating an attribute with the @Id annotation.
  4. I am trying to create a Privilege class with Annotations whose Primary Key is a String. I will assign them manually while inserting. Therefore no need for hibernate to generate a value for it. I'm trying to do something like that: @Id @GeneratedValue(generator = 'assigned') @Column(name = 'ROLENAME', nullable = false) private String roleName.

Oct 28, 2018  Hibernate also allows defining primary-keys made up of @ManyToOne associations combined with @Id annotation. In this case, the entity class should also fulfill the conditions of a primary-key class. In this case, the entity class should also fulfill the conditions of a primary-key class.

Every JPA entity must have a primary key.

You can specify a primary key as a single primitive, or JDK object type entity field (see 'Configuring a JPA Entity Simple Primary Key Field').

You can specify a composite primary key made up of one or more primitive, or JDK object types using a separate composite primary key class (see 'Configuring a JPA Entity Composite Primary Key Class').

You can either assign primary key values yourself, or you can associate a primary key field with a primary key value generator (see 'Configuring JPA Entity Automatic Primary Key Generation').

Configuring a JPA Entity Simple Primary Key Field

The simplest primary key is one you specify as a single primitive or JDK object type entity field (see 'Using Annotations').

Note:

For a JPA entity primary key field code example, see: http://www.oracle.com/technology/tech/java/oc4j/ejb3/howtos-ejb3/howtoejb30mappingannotations/doc/how-to-ejb30-mapping-annotations.html#id

Using Annotations

Example 7-1 shows how to use the @Id annotation to specify an entity field as the primary key. In this example, primary key values are generated using a table generator (see 'Configuring JPA Entity Automatic Primary Key Generation').

Hibernate Primary Key Generation

Configuring a JPA Entity Composite Primary Key Class

A composite primary key is usually made up of two or more primitive or JDK object types. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns. You can specify such a composite primary key with a separate composite primary key class (see 'Using Annotations')

A composite primary key class has the following characteristics:

  • It is a POJO class.

  • It must be public and must have a public no-argument constructor.

  • If you use property-based access, the properties of the primary key class must be public or protected.

    For other uses, see.Zombies are reanimated, mindless, decaying corpses with a hunger for human. Plants vs zombies garden warfare 2. They are the main antagonists of, as the objective of the game is to prevent them from eating the player's brains.

  • It must be serializable.

  • It must define equals and hashCode methods.

    The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.

You can make the composite primary key class either an embedded class owned by the entity class, or a nonembedded class whose fields you map to multiple fields or properties of the entity class. In the latter case, the names of primary key fields or properties in the composite primary key class and those of the entity class must correspond and their types must be the same.

Using Annotations

Example 7-2 shows a typical embeddable composite primary key class. Example 7-3 shows how to configure a JPA entity with this embedded composite primary key class using the @EmbeddedId annotation.

Hibernate Primary Key Generator AnnotationKey

Example 7-2 Embeddable Composite Primary Key Class

Example 7-3 JPA Entity With an Embedded Composite Primary Key Class

Example 7-5 shows a nonembedded composite primary key class. In this class, fields empName and birthDay must correspond in name and type to properties in the entity class. Example 7-5 shows how to configure a JPA entity with this nonembedded composite primary key class using the @IdClass annotation. Because entity class fields empName and birthDay are used in the primary key, you must also annotate them using the @Id annotation.

Example 7-4 Non-Embedded Composite Primary Key Class

Example 7-5 JPA Entity With a Mapped Composite Primary Key Class

Configuring JPA Entity Automatic Primary Key Generation

Typically, you associate a primary key field (see 'Configuring a JPA Entity Simple Primary Key Field') with a primary key value generator so that when an entity instance is created, a new, unique primary key value is assigned automatically.

Table 7-2 lists the types of primary key value generators that you can define.

Table 7-2 JPA Entity Primary Key Value Generators

TypeDescriptionFor more information, see ..

Generated Id Table

A database table that the container uses to store generated primary key values for entities. Typically shared by multiple entity types that use table-based primary key generation. Each entity type will typically use its own row in the table to generate the primary key values for that entity class. Primary key values are positive integers.

'Table Sequencing' in the Oracle TopLink Developer's Guide

Table Generator

A primary key generator, which you can reference by name, defined at one of the package, class, method, or field level. The level at which you define it will depend upon the desired visibility and sharing of the generator. No scoping or visibility rules are actually enforced. Oracle recommends that you define the generator at the level for which it will be used.

This generator is based on a database table.

'Table Sequencing' in the Oracle TopLink Developer's Guide

Sequence Generator

A primary key generator which you can reference by name, defined at one of the package, class, method, or field level. The level, at which you define it, will depend upon the desired visibility and sharing of the generator. No scoping or visibility rules are actually enforced. Oracle recommends that you define the generator at the level for which it will be used.

This generator is based on a sequence object that the database server provides.

'Native Sequencing With an Oracle Database Platform' in the Oracle TopLink Developer's Guide

'Native Sequencing With a Non-Oracle Database Platform' in the Oracle TopLink Developer's Guide


Note:

For an EJB 3.0 automatic primary key generation code example, see: http://www.oracle.com/technology/tech/java/oc4j/ejb3/howtos-ejb3/howtoejb30mappingannotations/doc/how-to-ejb30-mapping-annotations.html#sequencing

Using Annotations

Example 7-6 shows how to use the @TableGenerator annotation to specify a primary key value generator based on a database table. The TopLink JPA persistence provider will attempt to create this table at deployment time: if it cannot, then you must follow your database documentation to ensure that this table exists before deployment. When a new instance of Address is created, a new value for entity field id is obtained from ADDRESS_GENERATOR_TABLE. In this case, you must set the @GeneratedValue annotation attribute strategy to TABLE and generator to ADDRESS_TABLE_GENERATOR.

Example 7-6 GeneratedValue Strategy Table: @TableGenerator

Example 7-7 shows how to use the @SequenceGenerator annotation to specify a primary key value generator based on a sequence object provided by the database. The TopLink JPA persistence provider will attempt to create this object at deployment time: if it cannot, then you must follow your database documentation to ensure that this sequence object exists before deployment. When a new instance of Address is created, a new value for entity field id is obtained from database sequence object ADDRESS_SEQ. In this case, you must set the @GeneratedValue annotation attribute strategy to SEQUENCE and generator to ADDRESS_SEQUENCE_GENERATOR.

Example 7-7 GeneratedValue Strategy Sequence: @SequenceGenerator

Example 7-8 shows how to use the @GeneratedValue annotation to specify a primary key value generator based on a primary key identity column (autonumber column). When a new instance of Address is persisted, the database assigns a value to the identity column. In this case, the TopLink JPA persistence provider re-reads the inserted row and updates the in-memory Address entity to set id to this value.

Details
Written by Nam Ha Minh
Last Updated on 04 October 2019 Print Email

Entity Annotation In Hibernate

In this Hibernate tutorial, I will guide you how to configure Hibernate framework to work with Oracle database. The code examples below are tested with Hibernate 5 and Oracle Express database 18c. Here are the steps:

1. Use JDBC driver for Oracle database

A JDBC driver for Oracle must be present in your project’s classpath. Click here to download Oracle Database JDBC driver. Choose the version according to your Oracle database installation (you must have an account in Oracle website to download. Sign up is free).Extract the downloaded archive file and add the ojdbc8.jar to the project’s classpath, e.g. in Eclipse IDE:In case you use Maven, add the following dependency into the pom.xml file:Due to Oracle’s license restriction, you can’t download the driver directly from Maven’s repository, so you have to use dependency like that.


2. Specify database connection properties

If you use hibernate.cfg.xml file, specify connection properties for Oracle database as follows:Remember that the hibernate.cfg.xml file must be put in the src/main/resources folder of your project.In case you use JPA/Hibernate, specify database connection properties in the persistence.xml file like this:Note that the

Hibernate Annotation Mapping

persistence.xml file must be in the

Unique Key

src/main/resources/META-INF folder.

3. Create Sequence in Oracle database

Since Oracle doesn’t have auto-increment feature for primary key, you must use sequence instead. Use the following annotation for mapping the primary key field in a model class:For example, the Customer class that maps to the Customers table in the database:In this case, Hibernate will look for the sequence named HIBERNATE_SEQUENCE, so you need to create such a sequence in the database, using the following statement:If you want to use another sequence name, use the @SequenceGeneratorannotation as follows:Then create the sequence in the database accordingly:You can use SQLPlus or SQL Developer tool to create the sequence.

4. Hibernate Example Program

For your reference, the following example program uses Hibernate to persist a Customerobject to the Oracle database:In case you want to use JPA with Hibernate, here’s another sample program:As you can see, code remains the same for different databases. So to use Hibernate with Oracle database, you need to use proper JDBC driver, connection properties and create sequence.

Some Notes for Hibernate and Oracle database:

Hibernate Annotation Example

If somehow Hibernate inserts negative value for the ID column, you must specify allocation size for the sequence like this:The value of the allocation size attribute be as same as the value of the “increment by” field of the sequence in Oracle database.If the database table uses trigger to automatically insert values for the ID column, and the Hibernate’s SequenceGeneratordoesn’t work somehow, try this solution:You can also watch the video version here:

Other Hibernate Tutorials:


About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook.