2 Replies Latest reply on Feb 28, 2006 3:58 AM by cspada

    How to map a relation table.

    cspada

      Hi,
      i have A relation table between 2 object A and B, each has one id idA and idB

      In an existing model i have a relation table to associate object A and B with some other information (asootiation date, etc...).

      So the AB table is :
      idA long
      idB long
      createDate Date
      ...
      ...
      It's primary key is a composite key with idA and idB.

      My questions are :
      - how do i have to define the composite key in the AB mapping ? (using @IdClass or @embeddedId) ?
      - I want to crete the relations with A and B in the class but they are still part of the key, how do i define the columns names without error ou duplicate ?
      - Is it possible to update one of the 2 ids for a given association to simulate a OneToMany association ? Or do i delete the row to create a new one ?

      Thanks.
      Christophe.

        • 1. Re: How to map a relation table.
          mazz

          A very cool (and easy) way to know things like this is let the Hibernate Tools generate the Java code for you. At the very least, you can see how it codes up the annotations so you don't have to think about it. You can use the code as-is, modify it or throw it away. But at least you'll know how to define your mappings.

          The Hibernate Tools tutorials are simple and can get you up to speed to do this pretty quickly (this is assuming you are using the JBoss Eclipse IDE).

          FWIW: I have a relation table with the same thing (relationship between A and B each with each own ID - there is no special "third ID" in this table, its a true relationship table in the ER sense). The generated POJO spit out by the Hibernate Tools has a getId() annotated with @EmbeddedId with a ABId generated class. Each side of the relation (getA(), getB()) is annotated with a @JoinColumn and a @ManyToOne. There's some other tidbits in the generated code but that's the main things.

          Definitely use the Hibernate Tools, it'll make your life easier. At the very least to show you how to annotate your entity POJOs. I still don't understand all the intracacies of these ManyToOne, JoinColumn, etc. annotations - but I still managed to get my stuff working by simply running the code generator over my existing database schema and using the annotated POJOs it gave me. I didn't have to change any of the annotations it generated - it worked as-is. My schema was fairly simple (10 tables, nothing fancy or abnormal about the relationships between tables) so your mileage may vary.

          • 2. Re: How to map a relation table.
            cspada

            Thanks a lot.
            I'll have a look to hibernate tool right now.

            Christophe.