0 Replies Latest reply on Feb 6, 2007 11:51 AM by Jeromy Van Dusen

    One-to-One Mapping Creates Thousands of Unecessary Queries

    Jeromy Van Dusen Newbie

      I'm trying to create a simple one-to-one mapping between two tables using Hibernate 2.1.7, but the results are confusing me. What I'm really doing is simply adding a column to an existing table, but for various business reasons beyond my control, I cannot modify the existing table, so I've created a separate table to store the additional column, with the same primary key as the existing table.

      My mapping looks something like this (names have been changed to protect the innocent):

      <hibernate-mapping package="com.blah">
       <class name="Foo" table="foo">
       <id name="fooId" type="integer" column="foo_id" >
       <generator class="assigned"/>
       </id>
      
       <one-to-one name="bar" class="Bar" cascade="all" />
      
       <!-- some other columns follow... -->
       </class>
      </hibernate-mapping>
      


      <hibernate-mapping package="com.blah">
       <class name="Bar" table="bar">
       <id name="fooId" type="integer" column="foo_id" >
       <generator class="foreign">
       <param name="property">foo</param>
       </generator>
       </id>
      
       <one-to-one name="foo" class="Foo" constrained="true" />
      
       <!-- the extra columns follow... -->
       </class>
      </hibernate-mapping>
      


      I never retrieve a Bar instance. I only ever reference the properties of Bar via Foo's getBar() method. Nevertheless, when I turn on Hibernate's show_sql flag, I get the following query generated 1710 times for each page access:

      2007-02-06 10:01:23,125 INFO [STDOUT] Hibernate: select bar0_.foo_id as foo_id1_3_, foo1_.foo_id as foo1_0_, from bar bar0_ left outer join foo foo1_ on bar0_.foo_id=foo1_.foo_id where bar0_.foo_id=?
      


      I don't know why it's executing that query 1710 times (which is almost, but not quite, the number of rows in the foo table).

      Can anyone see anything wrong with my mapping files? Any idea why the query is starting with the bar table and left joining to the foo table, especially considering I never call Bar's getFoo() method (actually, the code I tested that generated the 1710 queries doesn't even call Foo's getBar() method, it merely retrieves a Foo instance)?

      Any help is greatly appreciated.