본문 바로가기

카테고리 없음

Jpa Tools Generate Composite Key Tables



The DDL script will DROP existing tables on the database and CREATE new tables, based on the entities in your project. To generate a DDL script: Right-click the JPA project in the Project Explorer and select JPA Tools Generate Tables from Entities. @GeneratedValue can only be used to generate key values for a primary key, it cannot generate combination for composite keys. – Rohit Jain Oct 24 '12 at 8:17 1. 4 options to generate primary keys 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.

Object-Relational Mappings: Generating JPA Entities

This document describes the following:


OEPE allows you to generate JPA entities using the entity generation tool called OEPE JPA Entity Generation Wizard.

Note that prior to using this tool, you should set up and configure the database connection, as well as add JPA support to your Eclipse project.

To generate JPA entities using the JPA Entity Generation Wizard, follow this procedure:

    1. Right-click your project in the Project Explorer and select JPA > Generate Custom JPA Entities from the drop-down menu, as Figure 1 shows. This will open the Generate Custom Entities dialog.



      Figure 1.
      Generating Custom JPA Entities

      Microsoft windows 7 key generator. Windows 7 keygen is available in six different editions that are Home Premium, Professional and Ultimate.

 

    1. In the Generate Custom Entities > Select Tables dialog, specify the database connection and the schema. This will populate the Tables list, as Figure 2 shows.
    2. From the Tables list, select database tables for which you want to generate entities, as Figure 2 shows.



      Figure 2.
      Generate Custom Entites Dialog

 

    1. Ensure that Synchronize Classes listed in persistence.xml is selected.
    2. Specify whether or not JDBC driver JARs should be added to the project classpath. Use this setting if your JPA project is running as a stand-alone Java application.
    3. Click Next.
    4. On the next screen, define properties of table associations. If you want to define new associations, click Create New Association. This will open the Create New Association dialog, as Figure 3 shows.



      Figure 3.
      Create New Association Dialog

 

    1. On the Create New Association > Association Tables dialog, specify the association tables, as well as the type of association you want to create by selecting either Simple Association or Many to many Association, and then click Next.
    2. On the Create New Association > Join Columns screen, specify the join columns between the tables by clicking Add, as Figure 4 shows.



      Figure 4.
      Create New Association Dialog - Join Columns

 

    1. On the Create New Association > Association Cardinality screen, specify the association cardinality of the relationship by selecting either Many to One, One to Many, or One to One, as Figure 5 shows, and then click Finish.



      Figure 5.
      Create New Association Dialog - Association Cardinality


      The Generate Custom Entities dialog will display the table association that you have created. You can edit the association by clicking on it and modifying the field values on the bottom panel, as Figure 6 shows, and then click Next.



      Figure 6.
      Table Association

 

  1. Skip entering values in the Generate Entities > Default Table Generation screen, as you are discouraged from using the default table generation, and click Next.
  2. In the Generate Custom Entities > Customize Individual Entities screen, specify generation properties for each indiviudual table and columns, as Figure 7 shows, and then click Finish.



    Figure 7.
    Table Association

 

Upon the completion of the OEPE JPA Entity Generation Wizard, the generated JPA entity classes are automatically added to your project's persistence.xml file, as Figure 8 and Figure 9 show.



Figure 8.
persistence.xml File

 



Figure 9.
Generated Persistent Class


Getting Started With the Oracle Database Plugin for Eclipse
Configuring a Persistence Provider for JPA Projects

Spring data jpa composite key


To set up a database connection using Eclipse IDE, follow this procedure:

    • Collect the information necessary to connect to your target database. This may include preparing the database schema.
      The following example shows a DDL script that you can use to create a database schema that Figure 4 demonstrates:



      Figure 10.
      Sample Database Schema

 

  • Define a database connection using the Eclipse IDE's New Connection Profile Wizard, as follows:
    • Select the database connection type. This could be Oracle or Generic JDBC connection, for example.
    • Select JDBC driver.
    • Specify connection properties.
    • Test the database to ensure the connection properties are set correctly.
  • Connect to the database and examine the database schema using the Data Source Exploerer. For more information, see Connecting to an Oracle Database.


In order to use JPA, you need to be working within either a Web, EJB or utility project that supports JPA facet (includes the required libraries).

To create a new Eclipse JPA project, follow this procedure:

    1. Right-click the Project Explorer and select New > Project from the drop-down menu. This will open the New Project dialog.
    2. Select JPA > JPA Project from the list, as Figure 11 shows, and then click Next.



      Figure 11.
      New Project Dialog

 

      This will open the

New JPA Project

      dialog, as

Figure 12

      shows.

 



Figure 12.
New JPA Project Dialog

 

  1. On the New JPA Project dialog, specify the following:
      • provide a name for your project;
      • select Oracle WebLogic Server v.N as your target runtime;
      • enter the appropriate value in Configuration field. To specify either EclipseLink or Oracle Kodo as your persistence provider, click Modify, and select either Java Persistence Library (EclipseLink), or a combination of Java Persistence Library (Oracle Kodo) and WebLogic Utility Module Extensions on the Project Facets dialog, as Figure 13 shows. For more information, see Configuring a Persistence Provider for JPA Projects.



        Figure 13.
        Project Facets Dialog - JPA Configuration


    • optionally, select Add project to an EAR;
    • click Next.
  2. Optionally, make modifications on the New JPA Project > JPA Facet screen, making sure you specify the database connection in the Connection field, and then click Finish.

 

You can also add JPA support to an existing Eclipse project as follows:

  • Right-click your project in Project Explorer and select Properties from the drop-down menu. This will open the Properties dialog.
  • Select Project Facets from the tree control on the left, and then select Java Persistence, as well as one of Java Persitence Library (EclipseLink) or Java Persitence Library (Oracle Kodo) from the Project Facet list. For more information, see Configuring a Persistence Provider for JPA Projects
  • Click Further configuration available... This will open the Modify Faceted Project dialog.
  • On the Modify Faceted Project dialog, make appropriate modifications, ensuring that you specify the database connection in the Connection field, and then click Next.
  • On the next screen, configure the JPA persistence provider libraries, and then click Finish.
  • Click Apply, and then OK on the Properties dialog.

The issue of the legacy database schema

Free

The problem definition

This tip starts with a simple description of the problem: defining a composite database key. This is a key that combines a number of columns to uniquely define the rows of a database table. Sometimes, composite keys are called natural keys or business keys. Composite keys are sometimes used because the choice of key relates in some way to the end-user business domain. To define a composite key, you simply take some attributes from the domain and combine them to provide the required degree of row uniqueness. The downside to composite keys is that they are a little difficult to design and code. Also, they tend to tie your database and ORM design to the original domain. The latter may or may not be a big issue.

Entity code

Listing 1 illustrates a Java class called BillingAddress. This class models the billing address for a person or an organization. The billing itself relates to another Java class called PurchaseOrder. There's nothing too amazing here — a purchase order is placed and a billing process ensues.

Listing 1. The BillingAddress class

An important point to note is that the class implements the Java Serializable interface. Notice also the line with the annotation @Embeddable. This annotation is the first piece of the composite key jigsaw puzzle. A Java class with the @Embeddable annotation can itself become a subcomponent of another class. That sounds a lot more complicated than it is. To illustrate, Listing 2 shows the PurchaseOrder class, which uses the BillingAddress class from Listing 1.

Listing 2. The PurchaseOrder class

I always find annotations a bit hard to follow, and Listing 2 is no exception, so I'll break it down into manageable chunks. The first annotation is @Entity, which indicates that the class is a database entity (that is, it will form part of the ORM solution). Typically, when you see the @Entity annotation, you can expect to see a corresponding database table. The latter is indicated by the next annotation — namely, @Table. I find when you break down the process in this way, it becomes easier to understand.

Next up in Listing 2 is the @IdClass annotation, which defines the composite key class reference. You may have noted that this annotation refers to the BillingAddress class from Listing 1. Skipping past the constructors in Listing 2, notice the @Id annotation. This is where the composite key is defined with nested @AttributeOverrides annotations. These annotations are used to define the composite key columns: 'STREET' and 'CITY' respectively.

Just after the annotations in Listing 2, can you spot two lines of duplicate code from Listing 1? The duplicate code is, of course, the two private data members for street and city. This duplication is required to create the composite key.

The database schema

So far, it's all been fairly technical. Now see this expressed in a more concrete fashion by generating a database schema. Listing 3 illustrates the schema from this ultra-simple ORM database design.

Listing 3. The database schema

You can see that the primary key is indeed a composite made up of the street and city fields. What does this look like in a real database — for example, one with a graphical user interface (GUI) tool? Before answering that, I write some simple client code to persist one or two entities to a database.

Listing 4 illustrates an excerpt of some code to instantiate objects of the classes defined earlier.

Listing 4. Some ORM client code

Composite

The code in Listing 4 illustrates the journey from PurchaseOrder object instantiation and setup all the way through to persistence of this object in the database. This really illustrates the magic that is ORM. Have a look at what happens.

To begin with, an instance of EntityManagerFactory is created, and this is, in turn, used to create an instance of EntityManager called em. The latter is then used to write the PurchaseOrder object instance to the database. The actual persistence into the database occurs as part of a transaction.

A transaction is a set of atomic actions that either all occur successfully or are rolled back in the case of error. As you can see from Listing 4, the EntityManager object is used to create an instance of EntityTransaction called tx. It is the latter object that wraps the unit of work in a transaction.

Notice the calls to persist() and commit(). It's important to remember that no changes to the database occur unless both of these invocations occur. This is the simple pattern of the Java Persistence API (JPA).

To complete the ORM tour, Figure 1 shows what the database looks like after running the code in Listing 4. The code was tested using an in-memory database called HSQLDB, and this product includes a simple GUI tool. The state of the HSQLDB database is shown in Figure 1. You can see that I ran an SQL query on the PURCHASE_ORDERS table. This table was created from the schema, which itself was created from the Java code in the earlier listings.

Figure 1. The populated database

In Figure 1, you can see the effect that this line of code from Listing 4 had: purchaseOrder.setItemName('My new computer'). The invocation of the setter code populated the associated column in the database row with the String data: 'My new computer.' In terms of workflow, you can think of the overall program run as the creation of a purchase order for a new computer followed by a billing process. All the steps in the workflow are implicitly stored in the database.

Jpa Tools Generate Composite Key Tables 2016

Concluding comments about composite keys

The composite key defined in listings 1 and 2 allows you to bundle a number of columns together. The combination of columns then provides the required uniqueness so you can have an arbitrary number of rows in the database table. You've seen how it's done. Now, you need to briefly understand why one might take this quirky approach to database design.

Probably the most common reason for using composite keys is for backwards-compatibility. In other words, it occurs in those cases where you need to integrate new database code into a legacy environment. I think it's quite unusual to intentionally design a database this way nowadays, so it's likely you'll only need to create composite keys where it is a long-established practice.

Foreign Key

In such cases, my experience is that it's pointless arguing against this approach. If composite keys are the standard, then that's not likely to change any time soon. In many cases, there may be masses of existing data already structured in this way. So, if a change is made from composite keys to numerical keys, then the legacy data has to be migrated. Also, there may be business processes that map onto the composite key data. The combination of all these factors may make composite key design a necessity.

Downloadable resources

Jpa Composite Id

Related topics

Spring Data Jpa Composite Key

  • Visit Sun's JPA wiki to learn more about the Java Persistence API for persistence and object/relational mapping for the Java EE platform.
  • Go to the Hibernate site for background reading, code downloads, and more.
  • Follow developerWorks on Twitter.
  • Download IBM product evaluation versions and get your hands on application development tools and middleware products from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®.