Specify Generated Value Of Composite Primary Keys In Jpa

Every JPA entity must have a primary key.

  1. Specify Generated Value Of Composite Primary Keys In Jpa 2017
  2. Sql Composite Primary Keys
  3. Foreign Keys
  4. Specify Generated Value Of Composite Primary Keys In Jpa Excel
  5. Specify Generated Value Of Composite Primary Keys In Jpa 2016

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').

JPA and Hibernate can do much more than just mapping a numerical primary key column to an entity attribute. You can use them to generate unique primary key values, to map and create UUIDs, to work with composite primary keys, and to use the same primary key value for associated entities. 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 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').

And if you want to persist a new entity, you need to set the primary key value programmatically. But with JPA and Hibernate you can do much more than that. You can: choose between different strategies to generate unique primary key values, use UUIDs and generate their values, map composite primary keys, share primary key values across. When a primary key field is defined the primary key value is automatically injected into that field by ObjectDB. The @GeneratedValue annotation specifies that the primary key is automatically allocated by ObjectDB. Automatic value generation is discussed in detail in the Generated Values section.

I've found this specific note in session 9.1.9 GeneratedValue Annotation from JPA specification: '43 Portable applications should not use the GeneratedValue annotation on other persistent fields or properties.' So, I presume that it is not possible to auto generate value for non primary key values at least using simply JPA. Device.id (Primary Key) Token.id (Primary Key) Question(s): (1) How do I set these up in Hibernate3 or MySQL5 code? (2) Am very new with SQL so would it be that the Device.id is the foreign key of User.userid and vice versa with Device and Token? Am very new to Hibernate 3 / JPA so would appreciate it if someone could help.

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').

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.

  • 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.

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

Specify Generated Value Of Composite Primary Keys In Jpa 2017

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

Specify

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.

Ranch Hand
posted 10 years ago
Hello there...
Created 3 JPA annotated classes:
User:

Device:

Token:

Am trying to set up ER relationships in Hibernate 3 / JPA (or even in MySQL 5) like this:
User has one to many Devices.
User.userid (Primary Key)
Device.id (Primary Key)
Device has one to one relationship with Token.
Device.id (Primary Key)
Token.id (Primary Key)
Question(s):
(1) How do I set these up in Hibernate3 or MySQL5 code?
(2) Am very new with SQL so would it be that the Device.id is the foreign key of User.userid and vice versa with Device and Token?
Am very new to Hibernate 3 / JPA so would appreciate it if someone could help...
Thank you and happy programming!
author and cow tipper
posted 10 years agoSo, you'll need instance variables:

User has one to many Devices.


So, the User class will has a List of devices, List devices = new ArrayList(); Put in setters and getters. Device will have an instance of a User. Then add your JPA annotations like usual.

Device has one to one relationship with Token.


Add instance variables - Devices has an instance of a Token, and a Token has an instance of a Device. Then perform the annotation mapping as usual with any one-to-one association.
Here's a good tutorial on mapping one-to-one relations with Hibernate and JPA: Primary
Mapping Associations with the Java Persistence API
There's a discussion of one-to-many mappings on that site as well.

Sql Composite Primary Keys

Keep asking questions, and let us know how you're getting along, including code snippets and any errors you have.
-Cameron McKenzie
Ranch Hand
posted 10 years ago
Cameron,
Yes, I checked out the tutorial and got my code working!
The tutorial does throw an exception however...
Created my tables like this:


Exam:

ExamDetail:

ExamApp:

When you run ExamApp this is what happens:

Question(s):
(1) In the CreateExam.sql query, you stated to place this:
KEY FK2FB81FB83A97F5 (detail_id),
CONSTRAINT FK2FB81FB83A97F5
What is the FK2FB81FB83A97F5 for and where do I create values like this for my own foreign keys?
(2) What is causing the exception?
Thank you for everything!
-James
author and cow tipper
posted 10 years ago
Well, in this case, you just forgot to add the Exam and ExamDetail to the HibernateConfig in the HibernateUtil class:

Creating a HibernateUtil Class
-Cameron McKenzie
Ranch Hand
posted 10 years ago
Cameron,
Thank you for your help! You stated these fields in your tutorial:
KEY FK2FB81FB83A97F5 (detail_id),
CONSTRAINT FK2FB81FB83A97F5
What is the FK2FB81FB83A97F5 for and where do I create values like this for my own foreign keys?
-James
author and cow tipper
posted 10 years ago
Oh, I have no idea what those are. I think it's just the identifier MySQL gives to the foreign key constraint. With the various classes added to the Hibernate Config, you can have Hibernate create your database tables for you.

Creating Tables with the SchemaExport create
-Cameron McKenzie

Foreign Keys

Ranch Hand
posted 10 years ago
Okay, cool... Thank you! I've used the SchemaExport mechanism before but still felt safer by creating tables in MySQL by using the scripts.
-James
author and cow tipper

Specify Generated Value Of Composite Primary Keys In Jpa Excel

posted 10 years ago

Specify Generated Value Of Composite Primary Keys In Jpa 2016

The nice thing is that the log files actually show you the scripts. In fact, I think if you do create(true,false) or something like that, it spits out the script in the log file, but doesn't actually connect to the database and create the tables, so you can see exactly what SQL, and it is SQL, that Hibernate will use. It's a great feature if you can do a 'top down' database design.
-Cameron McKenzie