3 Replies Latest reply on Jul 9, 2003 8:55 AM by noel.rocher

    JBoss 3.2 - pk & fk mini guide

    noel.rocher

      Hi all,

      With 3.0.x versions of JBoss I had a big problem when in a table foreign keys should be part of the primary key.
      The problem was that in the ejbCreate method of the CMP2.0 entity,
      1 - the row was created in the database
      2 - relation fields couldn't be a regular cmp fields
      3 - relation fields can only be set in ejbPostCreate method
      4 - fk_id should be defined in the create table as nullable
      This constraints led us to use artifacts to manage our relationships (id for relation tables with fk for the relation and unique constraints) and in some cases we were in a dead end (rows from the same table in distributed databases in an application for a fleet of vessels).

      ...

        • 1. Re: JBoss 3.2 - pk & fk mini guide
          noel.rocher

          With 3.2.x these problems are gone, foreign keys can be part of primary key (a field can be cmp and cmr). But there's still some other things to know.

          • 2. Re: JBoss 3.2 - pk & fk mini guide
            noel.rocher

            1 - You have a non nullable fk but not in the primary key.

            1.A - You can delay the constraint checking at the end of the transaction within your database.

            Example with PostgreSQL if you create your table as this :
            create MyTable(
            my_id int not null,
            fk_id int not null,
            CONSTRAINT PK_my_table primary key (my_id),
            CONSTRAINT FK_fk_table foreign key (fk_id)
            references (fk_table) DEFERRABLE INITIALLY
            DEFERRED);

            note: it could be a good solution to modify the foreign-key template for your db

            <fk-constraint-template>
            ALTER TABLE ?1 ADD CONSTRAINT ?2 FOREIGN KEY (?3) REFERENCES ?4 (?5) DEFERRABLE INITIALLY DEFERRED
            </fk-constraint-template>

            Then you don't need to declare any cmp fields for your cmr fields and you just have to set your relation in the postCreate method (just conform to the EJB spec)

            1.B - You cannot delay the constraint checking
            then you have to define a cmp fields for the foreign key in addition of the cmr. Then in the ejbCreate method, you can set the fk_ids as a cmp field and in the ejbPostCreate method you can set the relationship.


            2 - You have a fk in your pk

            Here, no choice, you need to make your fk_id field a cmr and cmp field, and in ejbCreate you have to set it.

            Noel

            • 3. Re: JBoss 3.2 - pk & fk mini guide
              noel.rocher


              For those of you that asked themselves why I've written in several parts I say : I had to track a bad character that made my post to fail. It took me 20 min to post all !
              Sorry