Making a one to many relation it to columns per entry of the many relation

CREATE TABLE main (id number, data varchar2(20));
INSERT INTO main values (1,'some data1');
INSERT INTO main values (2,'some data2');
CREATE TABLE sub(main_id number, data varchar2(20), value number);
INSERT INTO sub values (1,'data1', 10);
INSERT INTO sub values (1,'data2', 5);
INSERT INTO sub values (2,'data3', 10);
INSERT INTO sub values (2,'data4', 30);
INSERT INTO sub values (2,'data5', 20);
I want a result like this
id | data | sub1 | sub2 | sub3
1, some data1, data1, data2, NULL
2, some data2, data4, data5, data1
That is sub1 is the value sub.data that has the largest value, sub2 is the second largest and so on.
This is the closest I can get. Is there a way to make the where main_id = 1 dynamic so instead of 1 it refeers to the value of main.id? Or is there a different query that will give me the result I'm looking for?
SELECT main.id, main.data, sub1.data sub1, sub2.data sub2, sub3.data sub3
FROM main
full outer join
(SELECT main_id, data, value
FROM(SELECT main_id, data, value, rownum rn
FROM(SELECT *
FROM sub
WHERE main_id = 1
ORDER BY value desc))
WHERE rn = 1) sub1
on main.id = sub1.main_id
full outer join
(SELECT main_id, data, value
FROM(SELECT main_id, data, value, rownum rn
FROM(SELECT *
FROM sub
WHERE main_id = 1
ORDER BY value desc))
WHERE rn = 2) sub2
on main.id = sub2.main_id
full outer join
(SELECT main_id, data, value
FROM(SELECT main_id, data, value, rownum rn
FROM(SELECT *
FROM sub
WHERE main_id = 1
ORDER BY value desc))
WHERE rn = 3) sub3
on main.id = sub3.main_id
ID     DATA     SUB1     SUB2     SUB3
2     some data2     -      -      -
1     some data1     data1     data2     -

SQL> select main.id
  2       , main.data
  3       , max(decode(sub.rn,1,sub.data)) "sub1"
  4       , max(decode(sub.rn,2,sub.data)) "sub2"
  5       , max(decode(sub.rn,3,sub.data)) "sub3"
  6    from main
  7       , (select t.*, row_number() over (partition by main_id order by data) rn from sub t) sub
  8   where sub.main_id = main.id
  9   group by main.id
10       , main.data
11  /
        ID DATA                 sub1                 sub2                 sub3
         1 some data1           data1                data2
         2 some data2           data3                data4                data5
2 rijen zijn geselecteerd.Regards,
Rob.

Similar Messages

  • How to add one column for entry in the TLB screen?

    Hi all,
    Does anybody know how to add a customised column for free text in the TLB header screen? The reason is user needs to add ship or container no. This info will be later on interfaced via CIF exit to R/3.
    I think many of you have the same requirement.
    Thanks heaps!

    Thanks Digambar,
    Can you help to work out more detail on how to customize the code in the TLB screen?
    Are you thinking of adding one field in the table and making the ALV grid control editable? If you have any reference doc/link to do it, it would great!
    Cheers,

  • One to many relation doesn't work

    I tried without success to get a simple one to many relationship to work.
    The select works fine but
    I still have problems with insert.
    I have two tables on a existing schema:
    1     ANAG (ID_ANAG primary key,...)
    2     INDI (ID_INDI primary key, ID_ENTITA,...), where INDI.ID_ENTITA points
    to ANAG.ID_ANAG
    the two classes are:
    1     public class Anagrafica
         private int idAnag; //ID_ANAG
         private String ragSoc;
         private String ragSocFonet;
         private String codFisc;
         private String sesso;
         private Integer codTit;
         private Date dtNasc;
         private HashSet indis;
    2     public class Indirizzo
         private int idIndi; //ID_INDI
         private long idEntita; //ID_ENTITA
         private long tpEntita;
         private String indirizzo;
         private String localita;
         private String prov;
         private String cap;
         private Anagrafica anagrafica;
    the two metadata:
    1      anagrafica.jdo:
    <?xml version="1.0"?>
    <!-- This JDO Metadata file was auto-generated on 08/10/02 17.44.
    See http://www.solarmetric.com for Kodo JDO Documentation and examples. -->
    <jdo>
    <package name="domain">
    <class name="Anagrafica"
    identity-type="application"
    objectid-class="domain.AnagraficaPK">
    <extension key="table" value="ANAG" vendor-name="kodo"/>
    <extension key="class-column" value="none" vendor-name="kodo"/>
    <extension key="lock-column" value="none" vendor-name="kodo"/>
    <field name="idAnag" primary-key="true">
    <extension key="data-column" value="ID_ANAG"
    vendor-name="kodo"/>
    </field>
    <field name="ragSoc">
    <extension key="data-column" value="RAG_SOC"
    vendor-name="kodo"/>
    </field>
    <field name="ragSocFonet">
    <extension key="data-column" value="RAG_SOC_FONET"
    vendor-name="kodo"/>
    </field>
    <field name="codFisc">
    <extension key="data-column" value="COD_FISC"
    vendor-name="kodo"/>
    </field>
    <field name="sesso">
    <extension key="data-column" value="SESSO"
    vendor-name="kodo"/>
    </field>
    <field name="codTit">
    <extension key="data-column" value="COD_TIT"
    vendor-name="kodo"/>
    </field>
    <field name="dtNasc">
    <extension key="data-column" value="DT_NASC"
    vendor-name="kodo"/>
    </field>
    <field name="indis">
    <collection element-type="domain.Indirizzo"/>
    <extension vendor-name="kodo" key="table" value="INDI"/>
    <extension vendor-name="kodo" key="inverse"
    value="anagrafica"/>
    <extension vendor-name="kodo" key="idEntita-ref-column"
    value="ID_ANAG"/>
         </field>
    </class>
    </package>
    </jdo>
    2 Indirizzo.jdo
    <?xml version="1.0"?>
    <!-- This JDO Metadata file was auto-generated on 08/10/02 17.21.
    See http://www.solarmetric.com for Kodo JDO Documentation and examples. -->
    <jdo>
    <package name="domain">
    <class name="Indirizzo"
    identity-type="application" objectid-class="domain.IndiPK">
    <extension key="table" value="INDI" vendor-name="kodo"/>
    <extension key="class-column" value="none" vendor-name="kodo"/>
    <extension key="lock-column" value="none" vendor-name="kodo"/>
    <!--extension vendor-name="kodo" key="idEntita-data-column"
    value="ID_ENTITA"/-->
    <field name="idIndi" primary-key="true">
    <extension key="data-column" value="ID_INDI"
    vendor-name="kodo"/>
    </field>
    <field name="idEntita">
    <extension key="data-column" value="ID_ENTITA"
    vendor-name="kodo"/>
    </field>
    <field name="tpEntita">
    <extension key="data-column" value="TP_ENTITA"
    vendor-name="kodo"/>
    </field>
    <field name="indirizzo">
    <extension key="data-column" value="INDIRIZZO"
    vendor-name="kodo"/>
    </field>
    <field name="localita">
    <extension key="data-column" value="LOCALITA"
    vendor-name="kodo"/>
    </field>
    <field name="prov">
    <extension key="data-column" value="PROV"
    vendor-name="kodo"/>
    </field>
    <field name="cap">
    <extension key="data-column" value="CAP"
    vendor-name="kodo"/>
    </field>
    <field name="anagrafica">
    <extension vendor-name="kodo" key="idAnag-data-column"
    value="ID_ENTITA"/>
    </field>
    </class>
    </package>
    </jdo>
    The problem is:
    I create a new Anagrafica object and then I try to save it in the
    database. These are the SQL
    statements that are generated:
    INSERT INTO ANAG(DT_NASC, COD_FISC, RAG_SOC_FONET, SESSO, ID_ANAG,
    RAG_SOC, COD_TIT)
    VALUES (NULL, NULL, 'NATALE', NULL, 971963921, 'Natale', NULL)
    INSERT INTO INDI(TP_ENTITA, PROV, LOCALITA, ID_ENTITA, ID_INDI, INDIRIZZO,
    CAP)
    VALUES (0, NULL, NULL, 0, 971963921, 'via 25 dicembre', NULL)
    Why is the value of ID_ANAG (971963921) assigned to ID_INDI and not to
    ID_ENTITA?
    Regards
    Mirko

    Abe White wrote:
    <field name="indis">
    <collection element-type="domain.Indirizzo"/>
    <extension vendor-name="kodo" key="table" value="INDI"/>
    <extension vendor-name="kodo" key="inverse"
    value="anagrafica"/>
    <extension vendor-name="kodo" key="idEntita-ref-column"
    value="ID_ANAG"/>
         </field>
    Get rid of all extensions except the inverse:
    <field name="indis">
    <collection element-type="domain.Indirizzo"/>
    <extension vendor-name="kodo" key="inverse" value="anagrafica"/>
    </field>
    As in the examples in our documentation, all 1-many relations should only
    list their inverse 1-1 relation.
    Also, make sure your object model is consistent; i.e. make sure you'resetting
    both sides of the relation:
    indi.setAnagrafica (anag);
    anag.getIndis ().add (indi);
    Let us know if you continue to have problems.Hi Abe,
    I got rid of the unnecessary extensions and I set both sides of the
    relation as you suggest but I still have the same problem:
    INSERT INTO ANAG(ID_ANAG) VALUES (2088176453)
    INSERT INTO INDI(ID_INDI, ID_ENTITA) VALUES (2088176453, NULL)
    while I expect
    INSERT INTO ANAG(ID_ANAG) VALUES (2088176453)
    INSERT INTO INDI(ID_INDI, ID_ENTITA) VALUES (<some ID>, 2088176453)
    any ideas?
    regards

  • How to get data from three tables (A,B,C) having one to many relation between A and B .and having one to many reation between b and c

    i have  three tables A,B,C.  there is one to many relation between A and B. and one to many relation existed between table b and c . how will get data from these three tables

    check if this helps:
    select * --you can always frame your column set
    from tableA a
    left join tableB b on a.aid=b.aid
    left join tableC c on c.bid=b.bid
    This is just a general query. However, we can help you a lot more, if you can post the DDL + sample data and required output.
    Thanks,
    Jay
    <If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>

  • How to create one to many relation database based on existing Tables?

    Let say I have got 10 tables. Out of these 10 tables one table is used to navigate to other tables and at the some time providing some useful information. Therefore other 9 Tables have the identical structure.
    The question is, how can I convert these 10 tables into 2 tables, ie each row of first table correspond to the different data of the other table (one to many relation)?

    Hello,
    >>The question is, how can I convert these 10 tables into 2 tables, ie each row of first table correspond to the different data of the other table (one to many relation)?
    I do not quite understand what you ask and I doubt if Entity Framework supports this scenario, since you mentions these tables already exist, after importing them to the designed windows, we cannot modify them or it would throw an error shows the database
    and model is mismatched.
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • EJB relation One to Many - ClassCastException

    Hi !
    I created two CMP EJB entity Client and Address. There is a One to Many relation between them.
    When I deploy them on JBoss, I have no errors, and the correponding tables are created in the database. The EJB seems to work fine, but when I use a 'relation' method : myAddress.setClient(myClient) for instance. I get a ServerException.
    In the log of JBoss there is :
    ClassCastException : org.jboss.ejb.plugins.cmp.jdbc.bridge.JDBCCMRFieldBridge.SetInstanceValue(...)
    I think I have a problem in my descriptors or JBoss configuration.
    If u have an idea ...
    Thx

    sorry to whack a load of code in but i can't see where the problem is here is my ejb-jar.xml file:
    <ejb-jar>
         <enterprise-beans>
              <entity>
                   <description>This bean represents a copy item.</description>
                   <ejb-name>CopyEJB</ejb-name>
                   <home>com.RemoteCopyHome</home>
                   <remote>com.RemoteCopy</remote>
                   <local-home>com.LocalCopyHome</local-home>
                   <local>com.LocalCopy</local>
                   <ejb-class>com.CopyBean</ejb-class>
                   <persistence-type>Container</persistence-type>
                   <prim-key-class>java.lang.String</prim-key-class>
                   <reentrant>False</reentrant>
                   <cmp-version>2.x</cmp-version>
                   <abstract-schema-name>Copy</abstract-schema-name>
                   <cmp-field>
                        <field-name>copyid</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>quality</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>buyinprice</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>selloutprice</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>bookid</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>title</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>genre</field-name>
                   </cmp-field>
                   <primkey-field>copyid</primkey-field>
                   <security-identity>
                        <description></description>
                        <use-caller-identity></use-caller-identity>
                   </security-identity>
              </entity>
              <entity>
                   <description>This bean represents a supplier.</description>
                   <ejb-name>SupplierEJB</ejb-name>
                   <home>com.RemoteSupplierHome</home>
                   <remote>com.RemoteSupplier</remote>
                   <local-home>com.LocalSupplierHome</local-home>
                   <local>com.LocalSupplier</local>
                   <ejb-class>com.SupplierBean</ejb-class>
                   <persistence-type>Container</persistence-type>
                   <prim-key-class>java.lang.String</prim-key-class>
                   <reentrant>False</reentrant>
                   <cmp-version>2.x</cmp-version>
                   <abstract-schema-name>Supplier</abstract-schema-name>
                   <cmp-field>
                        <field-name>supplierid</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>name</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>address1</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>address2</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>address3</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>address4</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>postcode</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>email</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>telno</field-name>
                   </cmp-field>
                   <primkey-field>supplierid</primkey-field>
                   <security-identity>
                        <description></description>
                        <use-caller-identity></use-caller-identity>
                   </security-identity>
              </entity>
              <entity>
                   <description>This bean represents an edition.</description>
                   <ejb-name>EditionEJB</ejb-name>
                   <home>com.RemoteEditionHome</home>
                   <remote>com.RemoteEdition</remote>
                   <local-home>com.LocalEditionHome</local-home>
                   <local>com.LocalEdition</local>
                   <ejb-class>com.EditionBean</ejb-class>
                   <persistence-type>Container</persistence-type>
                   <prim-key-class>java.lang.String</prim-key-class>
                   <reentrant>False</reentrant>
                   <cmp-version>2.x</cmp-version>
                   <abstract-schema-name>Edition</abstract-schema-name>
                   <cmp-field>
                        <field-name>editionid</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>isbn</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>publisher</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>binding</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>other</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>edition</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>printdate</field-name>
                   </cmp-field>
                   <primkey-field>editionid</primkey-field>
                   <security-identity>
                        <description></description>
                        <use-caller-identity></use-caller-identity>
                   </security-identity>
              </entity>
              <entity>
                   <description>This bean represents an author.</description>
                   <ejb-name>AuthorEJB</ejb-name>
                   <home>com.RemoteAuthorHome</home>
                   <remote>com.RemoteAuthor</remote>
                   <local-home>com.LocalAuthorHome</local-home>
                   <local>com.LocalAuthor</local>
                   <ejb-class>com.AuthorBean</ejb-class>
                   <persistence-type>Container</persistence-type>
                   <prim-key-class>java.lang.String</prim-key-class>
                   <reentrant>False</reentrant>
                   <cmp-version>2.x</cmp-version>
                   <abstract-schema-name>Author</abstract-schema-name>
                   <cmp-field>
                        <field-name>authorid</field-name>
                   </cmp-field>
                   <cmp-field>
                        <field-name>name</field-name>
                   </cmp-field>
                   <primkey-field>authorid</primkey-field>
                   <security-identity>
                        <description></description>
                        <use-caller-identity></use-caller-identity>
                   </security-identity>
              </entity>
              <session>
                   <description>Supplier Function Session Bean</description>
                   <display-name>SupplierFunctionEJB</display-name>
                   <ejb-name>SupplierFunctionEJB</ejb-name>
                   <home>com.SupplierFunctionHome</home>
                   <remote>com.SupplierFunctionRemote</remote>
                   <ejb-class>com.SupplierFunctionSBean</ejb-class>
                   <session-type>Stateless</session-type>
                   <transaction-type>Container</transaction-type>
              </session>
              <session>
                   <description>Copy Function Session Bean</description>
                   <display-name>CopyFunctionEJB</display-name>
                   <ejb-name>CopyFunctionEJB</ejb-name>
                   <home>com.CopyFunctionHome</home>
                   <remote>com.CopyFunctionRemote</remote>
                   <ejb-class>com.CopyFunctionSBean</ejb-class>
                   <session-type>Stateless</session-type>
                   <transaction-type>Container</transaction-type>
              </session>
         </enterprise-beans>
         <relationships>
              <ejb-relation>
                   <ejb-relation-name>Supplier-Copy</ejb-relation-name>
                   <ejb-relationship-role>
                        <ejb-relationship-role-name>copy-recievedfrom-supplier</ejb-relationship-role-name>
                        <multiplicity>Many</multiplicity>
                        <cascade-delete></cascade-delete>
                        <relationship-role-source>
                             <ejb-name>CopyEJB</ejb-name>
                        </relationship-role-source>
                        <cmr-field>
                             <cmr-field-name>supplier</cmr-field-name>
                        </cmr-field>
                   </ejb-relationship-role>
                   <ejb-relationship-role>
                        <ejb-relationship-role-name>supplier-has-items</ejb-relationship-role-name>
                        <multiplicity>One</multiplicity>
                        <relationship-role-source>
                             <ejb-name>SupplierEJB</ejb-name>
                        </relationship-role-source>
                   </ejb-relationship-role>
              </ejb-relation>
              <ejb-relation>
                   <ejb-relation-name>Edition-Copy</ejb-relation-name>
                   <ejb-relationship-role>
                        <ejb-relationship-role-name>edition-has-items</ejb-relationship-role-name>
                        <multiplicity>One</multiplicity>
                        <relationship-role-source>
                             <ejb-name>EditionEJB</ejb-name>
                        </relationship-role-source>
                   </ejb-relationship-role>
                   <ejb-relationship-role>
                        <ejb-relationship-role-name>copy-is-a-edition</ejb-relationship-role-name>
                        <multiplicity>Many</multiplicity>
                        <cascade-delete></cascade-delete>
                        <relationship-role-source>
                             <ejb-name>CopyEJB</ejb-name>
                        </relationship-role-source>
                        <cmr-field>
                             <cmr-field-name>edition</cmr-field-name>
                        </cmr-field>
                   </ejb-relationship-role>
              </ejb-relation>
              <!--<ejb-relation>
                   <ejb-relation-name>Author-Copy</ejb-relation-name>
                   <ejb-relationship-role>
                        <ejb-relationship-role-name>copy-has-items</ejb-relationship-role-name>
                        <multiplicity>Many</multiplicity>                                     
        <relationship-role-source>
                             <ejb-name>AuthorEJB</ejb-name>
                        </relationship-role-source>
                        <cmr-field>
                             <cmr-field-name>copies</cmr-field-name>
                             <cmr-field-type>java.util.Set</cmr-field-type>
                        </cmr-field>
                   </ejb-relationship-role>
                   <ejb-relationship-role>
                        <ejb-relationship-role-name>copy-has-authors</ejb-relationship-role-name>
                        <multiplicity>Many</multiplicity>
                        <cascade-delete></cascade-delete>
                        <relationship-role-source>
                             <ejb-name>CopyEJB</ejb-name>
                        </relationship-role-source>
                        <cmr-field>
                             <cmr-field-name>authors</cmr-field-name>
                     <cmr-field-type>java.util.Set</cmr-field-type>     
                        </cmr-field>
                   </ejb-relationship-role>
              </ejb-relation>-->
         </relationships>
         <assembly-descriptor>
              <security-role>
                   <description>This role represents everyone who is allowed full access
             to the beans.</description>
                   <role-name>Subscribers</role-name>
              </security-role>
              <method-permission>
                   <role-name>Subscribers</role-name>
                   <method>
                        <ejb-name>CopyEJB</ejb-name>
                        <method-name>*</method-name>
                   </method>
                   <method>
                        <ejb-name>SupplierEJB</ejb-name>
                        <method-name>*</method-name>
                   </method>
              </method-permission>
              <container-transaction>
                   <method>
                        <ejb-name>CopyEJB</ejb-name>
                        <method-name>*</method-name>
                   </method>
                   <method>
                        <ejb-name>SupplierEJB</ejb-name>
                        <method-name>*</method-name>
                   </method>
                   <trans-attribute>Required</trans-attribute>
              </container-transaction>
         </assembly-descriptor>
    </ejb-jar>my session bean code can be found at
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=11&t=006578

  • Understanding objects relations one-to-many and many-to-many with flex4

    Hello, I'm a newbie on Flex 4.
    I read several examples and also the "one week training". What I couldn't find is how to manage relations among objects.
    I understood that objects coming from the server must be translated to value objects.
    Because I'm working with Spring, Hibernate and BlazeDS, I've several beans and relations defined with the annotations @OneToMany and @ManyToMany. These relations are managed using List, Set and Map objects.
    More precisaly, I've to create a flex datagrid, each row is an "author" objects. Cliccking a row, I need to load some other related objects (let's call them "documents").
    Auhtor and Documents objects are in a one-to-many relation.
    My questions are:
    1) Which is the correct way to handle related objects in Flex? This questions arise from the fact that there are two ways in order to manage such objects. The first is to load the parent object and them call related method in order to get child. For example author.getDocuments(). I get all the related objects (author+ all his documents) with just one call, the one to load the "author" object. BlazeDS doesn't support lazy loading.
    The second way, is to provide the parent ID to a method that loads the related objects. For example getDocuments(authorID). I need to make a query for each ID
    Obviously, the value objects we have to create with AS are different. In the first case, the author VO will have a ArrayCollection in order to manage documents.In the second case I'll not create this property.
    2) In Flex, which is the best way? is it possible to manage objects (documents) of objects (authors) with MXML?
    3) More in general, Flex experts people, what are used to do? Where I can find an example?
    Thank you
    Paolo

    Thank you Pablo.
    Regarding my question n.2, it is confused.
    Here what I meant:
    Let's suppose I work with VO and ArrayCollection (the first "way" I wrote above). To get "Documents" objects, I need to call author.getDocuments().
    Now, I'm not sure that I'm able to do the same with MXML and that is is the easiest way. I think it should be easier working with "Documents" object instead of Auhors in order to work with Documents.
    For example, in order to get autors I can write a CallResponder and use a token. To fill a datagrid I define a method like
    protected function dataGrid_creationCompleteHandler(event:Flex:Event):void
         getAuthorsResult.token = auhtorService.getAuthors();}
    Now in order to fill the grid, I can use  for example <mx:DataGridColumn dataField="lastname">. Very easy and clear.
    But now, if I need to extract the Document objects and visualize them inside anothee DataGrid, I don't know how to do.
    For example, in <mx:DataGridColumn> tag what I've to write in order to visualize a Document property, using an Author object?
    Fixing an Auhtor, I need to loop over each Documents, but how can I loop inside the MXML? Something like <mx:DataGridColum dataField="author.documentloopvariable....>
    It should be better to get Documents via a method like getDocuments(authorID). Now I get a token related to a CallResponder, and I can work at the same manner as the Author. Isn't it? But this is the second "way" I wrote above.
    Well, I hope my question in a little clear.
    thank you
    Pbesi

  • JPA: Issue with loading One To Many relation

    Hi All,
    I have a One to Many relation mapped as below
    @Entity
    @Table(name="ACCOUNT_TABLE")
    public class UserAccount {
         // Attributes
         @Id
         @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="USER_SEQ")
         @SequenceGenerator(name="USER_SEQ", sequenceName="USERS_SEQ",allocationSize=1)
         @Column(name="CLIENT_ID")
         private Long clientId;
         @Column(name="USER_ID")
         private String userId;
         @OneToMany(fetch=FetchType.LAZY, mappedBy="userAccount")
         @JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updatable=false)
         private List<UserRole> assignedRoles;
    @Entity
    @Table(name = "ROLE_TABLE")
    public class UserRole extends BaseEntity implements Serializable {
         private static final long serialVersionUID = -1651953276532642312L;
         @Id
         @Column(name = "USER_ID", length = 30, nullable=false, insertable=false, updatable=false)
         private String userId;
         @Column(name = "BUSINESS_CODE", length = 10, nullable=false, insertable=false, updatable=false)
         private String businessCode;
         @Column(name = "ROLE_NAME", length = 30, nullable=false, insertable=false, updatable=false)
         private String roleName;
         @ManyToOne()
         @JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updatable=false)
         private UserAccount userAccount;
    As you may have noticed, the tables are not joined on the Primary key of parent. This is legacy schema and I have to work with it.
    Account and Role are joined by the USER_ID column. This I specified by providing JoinColumn.
    Then I have a DAO to retrieve the relation based on user id.
    public class UserAccountDAOJPAImpl UserAccountDAO{
         private static final String USER_ACCOUNT_BY_USERID = "select distinct ua " +
         "from UserAccount ua " +
         "left outer join fetch ua.assignedRoles ar " +
         "where ua.userId = ?1 ";
         public UserAccount findByUserName(String userName){          
              UserAccount userAccount=null;
              List<UserAccount> userAccounts =null;
         Query query = this.entityManager.createQuery(USER_ACCOUNT_BY_USERID);
         query.setParameter(1, userName.toUpperCase());
         userAccounts = query.getResultList();
         if(!userAccounts.isEmpty()) {
              userAccount=userAccounts.get(0);
              return userAccount;
    When I test this code ( for the user Id I used in test there are 11 roles )
    The SQL generated is correct, when I run the SQL in PL/SQL Developer, it returns the results as expected.
    But the DAO method above returns one UserAccount object with List of 11 UserRole objects as expected. But all of these 11 UserRole objects are same, where as the query returns 11 different roles.
    I couldn't figure out what I was doing wrong.
    Any help is appreciated.
    thanks,
    Raghavan

    @OneToMany(fetch=FetchType.LAZY, mappedBy="userAccount")
    @JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updatable=false)
    private List<UserRole> assignedRoles;
    }What do you get when you remove this @JoinColumn annotation? It shouldn't be necessary. (user_id seems a little suspect as the join column name by the way, I would have expected role_id here...)

  • Primary one-to-many relation

    What is the best practice to identify the primary entity in a one-to-many relation?
    Lets asume the following:
    I have persons. (Table: PERSON, Primary Key: PERSON_ID)
    I have contact points (Table: CONTACT_POINTS, Foreign Key to PERSON_ID)
    In the E-Business Suite we have a field PRIMARY_FLAG on the CONTACT_POINTS table. This is either Y or N. Now it is upon the application, to verify that only one primary contact point is set. But there is no check in the database. You can have 2 lines, with primary_flag = 'Y'.
    This would make it heavy to do a simple select as:
    SELECT p.first_name, p.last_name, cp.phone_number FROM PERSON p, CONTACT_POINTS cp WHERE cp.PERSON_ID(+) = p.PERSON_ID AND cp.PRIMARY_FLAG(+) = 'Y'
    Because if you have, by mistake, 2 lines with PRIMARY_FLAG = 'Y', you would get 2 result lines in the query above, which is not wanted.
    A second way would be to have the PRIMARY_FLAG field is filled either with Y or NULL. In addition I can set a unique constrain over PERSON_ID and PRIMARY_FLAG and the database will block every try to add a second Y for one person. In that way I can be sure that I either have a primary contact point or I do not have one. So the query will result the same number of lines as there are in the PERSON table. BUT: whenever I go that way, I have to verify my application logic, that every change on the primary flag must set the old primary entry off and then insert or update the new primary entry.
    Which one is the best way, in practice? Are there other solutions? What are advantages ?
    Best Regards
    Alexander

    You can create unique function based index on your CONTACT_POINTS table as follows:
    (person_id, case when primary_flag = 'Y' then primary_flag else null end)
    So as soon as you'll insert another row with Y, you'll get error, but with other values like N, all will be OK.
    And yes - I think it is worth to check data integrity in DB :)
    Gints Plivna
    http://www.gplivna.eu

  • TopLink11 Tutorial problems with one-to-many relation

    Hi,
    I installed TopLink 11 and the related tutorial to work in a simple Eclipse project.
    Everthing works fine except for the storing of the one-to-many relation in the database.
    The tutorial works with employee, address and phone tables/classes. Plain Objects can be stored and one-to-one relations too. However when trying to store a one-to-many relation not the key of the related object (which is at that tome well known) but the object is tried to be entered
    in the Logfile I find:
    [TopLink Fine]: 2008.01.10 10:27:28.748--DatabaseSessionImpl(12916846)--Connection(9550256)--Thread(Thread[main,5,main])--INSERT INTO EMPLOYEE (EMP_ID, L_NAME, F_NAME, ADDR_ID, VERSION) VALUES (?, ?, ?, ?, ?)
         bind => [1501, Pascal, Blaise, 2252, 1]
    [TopLink Finer]: 2008.01.10 10:27:28.748--DatabaseSessionImpl(12916846)--Connection(9550256)--Thread(Thread[main,5,main])--commit transaction
    [TopLink Finer]: 2008.01.10 10:27:28.748--UnitOfWork(14858725)--Thread(Thread[main,5,main])--end unit of work commit
    [TopLink Finer]: 2008.01.10 10:27:28.748--UnitOfWork(14858725)--Thread(Thread[main,5,main])--release unit of work
    [TopLink Finer]: 2008.01.10 10:27:28.748--UnitOfWork(14858725)--Thread(Thread[main,5,main])--release unit of work
    [TopLink Finest]: 2008.01.10 10:27:28.748--UnitOfWork(18511661)--Thread(Thread[main,5,main])--Register the object Employee: Blaise Pascal
    [TopLink Finest]: 2008.01.10 10:27:28.748--UnitOfWork(18511661)--Thread(Thread[main,5,main])--Execute query DoesExistQuery()
    [TopLink Finer]: 2008.01.10 10:28:58.370--UnitOfWork(18511661)--Thread(Thread[main,5,main])--begin unit of work commit
    [TopLink Finer]: 2008.01.10 10:28:58.370--DatabaseSessionImpl(12916846)--Connection(9550256)--Thread(Thread[main,5,main])--begin transaction
    [TopLink Finest]: 2008.01.10 10:28:58.370--UnitOfWork(18511661)--Thread(Thread[main,5,main])--Execute query UpdateObjectQuery(Employee: Blaise Pascal)
    [TopLink Finest]: 2008.01.10 10:28:58.386--UnitOfWork(18511661)--Thread(Thread[main,5,main])--Execute query InsertObjectQuery(PhoneNumber[desk]: (603) 123-4567)
    [TopLink Fine]: 2008.01.10 10:28:58.386--DatabaseSessionImpl(12916846)--Connection(9550256)--Thread(Thread[main,5,main])--INSERT INTO PHONE (P_NUMBER, EMP_ID, AREA_CODE, TYPE) VALUES (?, ?, ?, ?)
         bind => [1234567, {Employee: Blaise Pascal}, 603, desk]
    [TopLink Warning]: 2008.01.10 10:28:58.511--UnitOfWork(18511661)--Thread(Thread[main,5,main])--Local Exception Stack:
    Exception [TOPLINK-4002] (Oracle TopLink - 11g Technology Preview 3 (11.1.1.0.0) (Build 071214)): oracle.toplink.exceptions.DatabaseException
    Internal Exception: java.sql.SQLException: Ungültiger Spaltentyp Error Code: 17004
    the highlighted section should be 1501 (the key of the employee record)
    Any ideas how to fix this?
    Thanks Erika

    Erika,
    You need to specify the other side of the relationship (on the PhoneNumber side), which is done by putting a @ManyToOne annotation on the "employee" attribute in PhoneNumber. That will cause TopLink to know that it is a relationship and not a basic mapping.
    -Mike

  • Unable to read one-to-many relations using Hibernate

    Hi,
    I am trying with a very simple one-to-many relationship. When I am storing the objects, there are no problems. But when I am trying to read out the collection, it says invalid descriptor index. Please help.
    Regards,
    Hibernate version:
    hibernate-3.1rc2
    Mapping documents:
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
         <class name="Parent">
              <id name="id">
                   <generator class="identity"/>
              </id>
              <set name="children">
                   <key column="parent_id"/>
                   <one-to-many class="Child"/>
              </set>
         </class>
         <class name="Child">
              <id name="id">
                   <generator class="identity"/>
              </id>
              <property name="name"/>
         </class>
    </hibernate-mapping>
    Code between sessionFactory.openSession() and session.close():
    The Parent class:
    public class Parent
         private Long id ;     
         private Set children;
         Parent(){}
         public Long getId()
              return id;
         public void setId(Long id)
              this.id=id;
         public Set getChildren()
              return children;
         public void setChildren(Set children)
              this.children=children;
    The Child class:
    public class Child
         private Long id;
         private String name;
         Child(){}
         public Long getId()
              return id;
         private void setId(Long id)
              this.id=id;
         public String getName()
              return name;
         public void setName(String name)
              this.name=name;
    The Main class:
    public class PCManager
         public static void main(String[] args)
              PCManager mgr = new PCManager();
              List lt = null;
              if (args[0].equals("store"))
                   mgr.createAndStoreParent(new HashSet(3));
              else if (args[0].equals("list"))
                   mgr.listEvents();
              HibernateUtil.getSessionFactory().close();
         private void createAndStoreParent(HashSet s)
              HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
              Parent p1 = new Parent();
              int size = 3;
              for (int i=size; i>0; i--)
                   Child c = new Child();
                   c.setName("Child"+i);
                   s.add(c);
              p1.setChildren (s);
              Iterator elems = s.iterator();
              do {     
                   Child ch = (Child) elems.next();
                   HibernateUtil.getSessionFactory().getCurrentSession().save(ch);
              }while(elems.hasNext());
              HibernateUtil.getSessionFactory().getCurrentSession().save(p1);
              HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
         private void listEvents()
              HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
              Parent result = (Parent) HibernateUtil.getSessionFactory().getCurrentSession().load(Parent.class, new Long(1));
              System.out.println("Id is :"+ result.getId());
              Set children = result.getChildren();
              Iterator elems = children.iterator();
              do {     
                   Child ch = (Child) elems.next();
                   System.out.println("Child Name"+ ch.getName());
              }while(elems.hasNext());
              HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();          
    Full stack trace of any exception that occurs:
    When I run with "hbm2ddl.auto" property as validate and trying to list the contents, I get the following out put.
    C:\Documents and Settings\mirza\Desktop\hibernate-3.1rc2\MyHibernate>ant run -Da
    ction=list
    Buildfile: build.xml
    clean:
    [delete] Deleting directory C:\Documents and Settings\mirza\Desktop\hibernate
    -3.1rc2\MyHibernate\bin
    [mkdir] Created dir: C:\Documents and Settings\mirza\Desktop\hibernate-3.1rc
    2\MyHibernate\bin
    copy-resources:
    [copy] Copying 4 files to C:\Documents and Settings\mirza\Desktop\hibernate
    -3.1rc2\MyHibernate\bin
    compile:
    [javac] Compiling 5 source files to C:\Documents and Settings\mirza\Desktop\
    hibernate-3.1rc2\MyHibernate\bin
    run:
    [java] 09:09:23,433 INFO Environment:474 - Hibernate 3.1 rc2
    [java] 09:09:23,449 INFO Environment:489 - loaded properties from resource
    hibernate.properties: {hibernate.cglib.use_reflection_optimizer=true, hibernate
    .cache.provider_class=org.hibernate.cache.HashtableCacheProvider, hibernate.dial
    ect=org.hibernate.dialect.SQLServerDialect, hibernate.max_fetch_depth=1, hiberna
    te.jdbc.use_streams_for_binary=true, hibernate.format_sql=true, hibernate.query.
    substitutions=yes 'Y', no 'N', hibernate.proxool.pool_alias=pool1, hibernate.cac
    he.region_prefix=hibernate.test, hibernate.jdbc.batch_versioned_data=true, hiber
    nate.connection.pool_size=1}
    [java] 09:09:23,465 INFO Environment:519 - using java.io streams to persis
    t binary types
    [java] 09:09:23,465 INFO Environment:520 - using CGLIB reflection optimize
    r
    [java] 09:09:23,481 INFO Environment:550 - using JDK 1.4 java.sql.Timestam
    p handling
    [java] 09:09:23,559 INFO Configuration:1257 - configuring from resource: /
    hibernate.cfg.xml
    [java] 09:09:23,559 INFO Configuration:1234 - Configuration resource: /hib
    ernate.cfg.xml
    [java] 09:09:23,872 INFO Configuration:460 - Reading mappings from resourc
    e: PCMapping.hbm.xml
    [java] 09:09:24,013 INFO HbmBinder:266 - Mapping class: Parent -> Parent
    [java] 09:09:24,045 INFO HbmBinder:266 - Mapping class: Child -> Child
    [java] 09:09:24,045 INFO Configuration:1368 - Configured SessionFactory: n
    ull
    [java] 09:09:24,061 INFO Configuration:1014 - processing extends queue
    [java] 09:09:24,061 INFO Configuration:1018 - processing collection mappin
    gs
    [java] 09:09:24,061 INFO HbmBinder:2233 - Mapping collection: Parent.child
    ren -> Child
    [java] 09:09:24,076 INFO Configuration:1027 - processing association prope
    rty references
    [java] 09:09:24,076 INFO Configuration:1049 - processing foreign key const
    raints
    [java] 09:09:24,155 INFO DriverManagerConnectionProvider:41 - Using Hibern
    ate built-in connection pool (not for production use!)
    [java] 09:09:24,170 INFO DriverManagerConnectionProvider:42 - Hibernate co
    nnection pool size: 1
    [java] 09:09:24,170 INFO DriverManagerConnectionProvider:45 - autocommit m
    ode: false
    [java] 09:09:24,170 INFO DriverManagerConnectionProvider:80 - using driver
    : sun.jdbc.odbc.JdbcOdbcDriver at URL: jdbc:odbc:MySQL
    [java] 09:09:24,170 INFO DriverManagerConnectionProvider:86 - connection p
    roperties: {}
    [java] 09:09:24,264 INFO SettingsFactory:77 - RDBMS: Microsoft SQL Server,
    version: 08.00.0194
    [java] 09:09:24,264 INFO SettingsFactory:78 - JDBC driver: JDBC-ODBC Bridg
    e (SQLSRV32.DLL), version: 2.0001 (03.85.1117)
    [java] 09:09:24,296 INFO Dialect:100 - Using dialect: org.hibernate.dialec
    t.SQLServerDialect
    [java] 09:09:24,311 INFO TransactionFactoryFactory:31 - Using default tran
    saction strategy (direct JDBC transactions)
    [java] 09:09:24,327 INFO TransactionManagerLookupFactory:33 - No Transacti
    onManagerLookup configured (in JTA environment, use of read-write or transaction
    al second-level cache is not recommended)
    [java] 09:09:24,327 INFO SettingsFactory:125 - Automatic flush during befo
    reCompletion(): disabled
    [java] 09:09:24,327 INFO SettingsFactory:129 - Automatic session close at
    end of transaction: disabled
    [java] 09:09:24,343 INFO SettingsFactory:144 - Scrollable result sets: ena
    bled
    [java] 09:09:24,343 INFO SettingsFactory:152 - JDBC3 getGeneratedKeys(): d
    isabled
    [java] 09:09:24,343 INFO SettingsFactory:160 - Connection release mode: au
    to
    [java] 09:09:24,358 INFO SettingsFactory:184 - Maximum outer join fetch de
    pth: 1
    [java] 09:09:24,358 INFO SettingsFactory:187 - Default batch fetch size: 1
    [java] 09:09:24,358 INFO SettingsFactory:191 - Generate SQL with comments:
    disabled
    [java] 09:09:24,358 INFO SettingsFactory:195 - Order SQL updates by primar
    y key: disabled
    [java] 09:09:24,358 INFO SettingsFactory:338 - Query translator: org.hiber
    nate.hql.ast.ASTQueryTranslatorFactory
    [java] 09:09:24,374 INFO ASTQueryTranslatorFactory:21 - Using ASTQueryTran
    slatorFactory
    [java] 09:09:24,374 INFO SettingsFactory:203 - Query language substitution
    s: {no='N', yes='Y'}
    [java] 09:09:24,374 INFO SettingsFactory:209 - Second-level cache: enabled
    [java] 09:09:24,374 INFO SettingsFactory:213 - Query cache: disabled
    [java] 09:09:24,374 INFO SettingsFactory:325 - Cache provider: org.hiberna
    te.cache.HashtableCacheProvider
    [java] 09:09:24,374 INFO SettingsFactory:228 - Optimize cache for minimal
    puts: disabled
    [java] 09:09:24,374 INFO SettingsFactory:233 - Cache region prefix: hibern
    ate.test
    [java] 09:09:24,405 INFO SettingsFactory:237 - Structured second-level cac
    he entries: disabled
    [java] 09:09:24,437 INFO SettingsFactory:257 - Echoing all SQL to stdout
    [java] 09:09:24,452 INFO SettingsFactory:264 - Statistics: disabled
    [java] 09:09:24,452 INFO SettingsFactory:268 - Deleted entity synthetic id
    entifier rollback: disabled
    [java] 09:09:24,452 INFO SettingsFactory:283 - Default entity-mode: POJO
    [java] 09:09:24,593 INFO SessionFactoryImpl:155 - building session factory
    [java] 09:09:24,938 INFO SessionFactoryObjectFactory:82 - Not binding fact
    ory to JNDI, no JNDI name configured
    [java] 09:09:24,954 INFO SchemaValidator:99 - Running schema validator
    [java] 09:09:24,954 INFO SchemaValidator:107 - fetching database metadata
    [java] 09:09:24,954 INFO Configuration:1014 - processing extends queue
    [java] 09:09:24,954 INFO Configuration:1018 - processing collection mappin
    gs
    [java] 09:09:24,954 INFO Configuration:1027 - processing association prope
    rty references
    [java] 09:09:24,954 INFO Configuration:1049 - processing foreign key const
    raints
    [java] 09:09:24,985 WARN JDBCExceptionReporter:71 - SQL Error: 0, SQLState
    : S1002
    [java] 09:09:24,985 ERROR JDBCExceptionReporter:72 - [Microsoft][ODBC SQL S
    erver Driver]Invalid Descriptor Index
    [java] 09:09:25,001 ERROR SchemaValidator:129 - Error closing connection
    [java] java.sql.SQLException: [Microsoft][ODBC SQL Server Driver]Invalid transaction state
    [java] Initial SessionFactory creation failed.org.hibernate.exception.Gener
    icJDBCException: could not get table metadata: Child
    [java] java.lang.ExceptionInInitializerError
    [java] at HibernateUtil.<clinit>(Unknown Source)
    [java] at PCManager.listEvents(Unknown Source)
    [java] at PCManager.main(Unknown Source)
    [java] Caused by: org.hibernate.exception.GenericJDBCException: could not g
    et table metadata: Child
    [java] at org.hibernate.exception.SQLStateConverter.handledNonSpecificE
    xception(SQLStateConverter.java:91)
    [java] at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6879)
    [java] at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7036)
    [java] at sun.jdbc.odbc.JdbcOdbc.SQLDisconnect(JdbcOdbc.java:2988)
    [java] at sun.jdbc.odbc.JdbcOdbcDriver.disconnect(JdbcOdbcDriver.java:9
    80)
    [java] at sun.jdbc.odbc.JdbcOdbcConnection.close(JdbcOdbcConnection.jav
    a:739)
    [java] at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaVal
    idator.java:125)
    [java] at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryIm
    pl.java:299)
    [java] at org.hibernate.cfg.Configuration.buildSessionFactory(Configura
    tion.java:1145)
    [java] at HibernateUtil.<clinit>(Unknown Source)
    [java] at org.hibernate.exception.SQLStateConverter.convert(SQLStateCon
    verter.java:79)
    [java] at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExcep
    tionHelper.java:43)
    [java] at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExcep
    tionHelper.java:29)
    [java] at org.hibernate.tool.hbm2ddl.DatabaseMetadata.getTableMetadata(
    DatabaseMetadata.java:100)
    [java] at org.hibernate.cfg.Configuration.validateSchema(Configuration.
    java:946)
    [java] at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaVal
    idator.java:116)
    [java] at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryIm
    pl.java:299)
    [java] at org.hibernate.cfg.Configuration.buildSessionFactory(Configura
    tion.java:1145)
    [java] ... 3 more
    [java] Caused by: java.sql.SQLException: [Microsoft][ODBC SQL Server Driver
    ]Invalid Descriptor Index
    [java] at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6879)
    [java] at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7036)
    [java] at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(JdbcOdbc.java:3862)
    [java] at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(JdbcOdbcResultS
    et.java:5561)
    [java] at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.j
    ava:338)
    [java] at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.j
    ava:395)
    [java] at PCManager.listEvents(Unknown Source)
    [java] at PCManager.main(Unknown Source)
    [java] at org.hibernate.tool.hbm2ddl.TableMetadata.<init>(TableMetadata
    .java:30)
    [java] at org.hibernate.tool.hbm2ddl.DatabaseMetadata.getTableMetadata(
    DatabaseMetadata.java:85)
    [java] ... 7 more
    [java] Exception in thread "main"
    [java] Java Result: 1
    BUILD SUCCESSFUL
    Total time: 4 seconds
    Name and version of the database you are using:
    Microsoft SQLServer2000
    The generated SQL (show_sql=true):
    When the program is run with "hbm2ddl.auto" property as create, I get the following output.
    C:\Documents and Settings\mirza\Desktop\hibernate-3.1rc2\MyHibernate>ant run -Daction=store
    Buildfile: build.xml
    clean:
    [delete] Deleting directory C:\Documents and Settings\mirza\Desktop\hibernate
    -3.1rc2\MyHibernate\bin
    [mkdir] Created dir: C:\Documents and Settings\mirza\Desktop\hibernate-3.1rc
    2\MyHibernate\bin
    copy-resources:
    [copy] Copying 4 files to C:\Documents and Settings\mirza\Desktop\hibernate
    -3.1rc2\MyHibernate\bin
    compile:
    [javac] Compiling 5 source files to C:\Documents and Settings\mirza\Desktop\
    hibernate-3.1rc2\MyHibernate\bin
    run:
    [java] 09:12:54,820 INFO Environment:474 - Hibernate 3.1 rc2
    [java] 09:12:54,836 INFO Environment:489 - loaded properties from resource
    hibernate.properties: {hibernate.cglib.use_reflection_optimizer=true, hibernate
    .cache.provider_class=org.hibernate.cache.HashtableCacheProvider, hibernate.dial
    ect=org.hibernate.dialect.SQLServerDialect, hibernate.max_fetch_depth=1, hiberna
    te.jdbc.use_streams_for_binary=true, hibernate.format_sql=true, hibernate.query.
    substitutions=yes 'Y', no 'N', hibernate.proxool.pool_alias=pool1, hibernate.cac
    he.region_prefix=hibernate.test, hibernate.jdbc.batch_versioned_data=true, hiber
    nate.connection.pool_size=1}
    [java] 09:12:54,852 INFO Environment:519 - using java.io streams to persis
    t binary types
    [java] 09:12:54,852 INFO Environment:520 - using CGLIB reflection optimize
    r
    [java] 09:12:54,867 INFO Environment:550 - using JDK 1.4 java.sql.Timestam
    p handling
    [java] 09:12:54,946 INFO Configuration:1257 - configuring from resource: /
    hibernate.cfg.xml
    [java] 09:12:54,946 INFO Configuration:1234 - Configuration resource: /hib
    ernate.cfg.xml
    [java] 09:12:55,259 INFO Configuration:460 - Reading mappings from resourc
    e: PCMapping.hbm.xml
    [java] 09:12:55,400 INFO HbmBinder:266 - Mapping class: Parent -> Parent
    [java] 09:12:55,447 INFO HbmBinder:266 - Mapping class: Child -> Child
    [java] 09:12:55,447 INFO Configuration:1368 - Configured SessionFactory: n
    ull
    [java] 09:12:55,447 INFO Configuration:1014 - processing extends queue
    [java] 09:12:55,447 INFO Configuration:1018 - processing collection mappin
    gs
    [java] 09:12:55,447 INFO HbmBinder:2233 - Mapping collection: Parent.child
    ren -> Child
    [java] 09:12:55,463 INFO Configuration:1027 - processing association prope
    rty references
    [java] 09:12:55,479 INFO Configuration:1049 - processing foreign key const
    raints
    [java] 09:12:55,557 INFO DriverManagerConnectionProvider:41 - Using Hibern
    ate built-in connection pool (not for production use!)
    [java] 09:12:55,557 INFO DriverManagerConnectionProvider:42 - Hibernate co
    nnection pool size: 1
    [java] 09:12:55,557 INFO DriverManagerConnectionProvider:45 - autocommit m
    ode: false
    [java] 09:12:55,573 INFO DriverManagerConnectionProvider:80 - using driver
    : sun.jdbc.odbc.JdbcOdbcDriver at URL: jdbc:odbc:MySQL
    [java] 09:12:55,573 INFO DriverManagerConnectionProvider:86 - connection p
    roperties: {}
    [java] 09:12:55,651 INFO SettingsFactory:77 - RDBMS: Microsoft SQL Server,
    version: 08.00.0194
    [java] 09:12:55,667 INFO SettingsFactory:78 - JDBC driver: JDBC-ODBC Bridg
    e (SQLSRV32.DLL), version: 2.0001 (03.85.1117)
    [java] 09:12:55,682 INFO Dialect:100 - Using dialect: org.hibernate.dialec
    t.SQLServerDialect
    [java] 09:12:55,698 INFO TransactionFactoryFactory:31 - Using default tran
    saction strategy (direct JDBC transactions)
    [java] 09:12:55,714 INFO TransactionManagerLookupFactory:33 - No Transacti
    onManagerLookup configured (in JTA environment, use of read-write or transaction
    al second-level cache is not recommended)
    [java] 09:12:55,714 INFO SettingsFactory:125 - Automatic flush during befo
    reCompletion(): disabled
    [java] 09:12:55,714 INFO SettingsFactory:129 - Automatic session close at
    end of transaction: disabled
    [java] 09:12:55,729 INFO SettingsFactory:144 - Scrollable result sets: ena
    bled
    [java] 09:12:55,729 INFO SettingsFactory:152 - JDBC3 getGeneratedKeys(): d
    isabled
    [java] 09:12:55,745 INFO SettingsFactory:160 - Connection release mode: au
    to
    [java] 09:12:55,745 INFO SettingsFactory:184 - Maximum outer join fetch de
    pth: 1
    [java] 09:12:55,745 INFO SettingsFactory:187 - Default batch fetch size: 1
    [java] 09:12:55,745 INFO SettingsFactory:191 - Generate SQL with comments:
    disabled
    [java] 09:12:55,745 INFO SettingsFactory:195 - Order SQL updates by primar
    y key: disabled
    [java] 09:12:55,745 INFO SettingsFactory:338 - Query translator: org.hiber
    nate.hql.ast.ASTQueryTranslatorFactory
    [java] 09:12:55,777 INFO ASTQueryTranslatorFactory:21 - Using ASTQueryTran
    slatorFactory
    [java] 09:12:55,792 INFO SettingsFactory:203 - Query language substitution
    s: {no='N', yes='Y'}
    [java] 09:12:55,792 INFO SettingsFactory:209 - Second-level cache: enabled
    [java] 09:12:55,792 INFO SettingsFactory:213 - Query cache: disabled
    [java] 09:12:55,792 INFO SettingsFactory:325 - Cache provider: org.hiberna
    te.cache.HashtableCacheProvider
    [java] 09:12:55,808 INFO SettingsFactory:228 - Optimize cache for minimal
    puts: disabled
    [java] 09:12:55,808 INFO SettingsFactory:233 - Cache region prefix: hibern
    ate.test
    [java] 09:12:55,808 INFO SettingsFactory:237 - Structured second-level cac
    he entries: disabled
    [java] 09:12:55,839 INFO SettingsFactory:257 - Echoing all SQL to stdout
    [java] 09:12:55,839 INFO SettingsFactory:264 - Statistics: disabled
    [java] 09:12:55,839 INFO SettingsFactory:268 - Deleted entity synthetic id
    entifier rollback: disabled
    [java] 09:12:55,839 INFO SettingsFactory:283 - Default entity-mode: POJO
    [java] 09:12:55,980 INFO SessionFactoryImpl:155 - building session factory
    [java] 09:12:56,325 INFO SessionFactoryObjectFactory:82 - Not binding fact
    ory to JNDI, no JNDI name configured
    [java] 09:12:56,341 INFO Configuration:1014 - processing extends queue
    [java] 09:12:56,341 INFO Configuration:1018 - processing collection mappin
    gs
    [java] 09:12:56,341 INFO Configuration:1027 - processing association prope
    rty references
    [java] 09:12:56,341 INFO Configuration:1049 - processing foreign key const
    raints
    [java] 09:12:56,356 INFO Configuration:1014 - processing extends queue
    [java] 09:12:56,356 INFO Configuration:1018 - processing collection mappin
    gs
    [java] 09:12:56,356 INFO Configuration:1027 - processing association prope
    rty references
    [java] 09:12:56,372 INFO Configuration:1049 - processing foreign key const
    raints
    [java] 09:12:56,372 INFO SchemaExport:153 - Running hbm2ddl schema export
    [java] 09:12:56,388 DEBUG SchemaExport:171 - import file not found: /import
    .sql
    [java] 09:12:56,388 INFO SchemaExport:180 - exporting generated schema to
    database
    [java] 09:12:56,403 DEBUG SchemaExport:283 -
    [java] alter table Child
    [java] drop constraint FK3E104FC976A59A
    [java] 09:12:56,466 DEBUG SchemaExport:283 -
    [java] drop table Child
    [java] 09:12:56,544 DEBUG SchemaExport:283 -
    [java] drop table Parent
    [java] 09:12:56,654 DEBUG SchemaExport:283 -
    [java] create table Child (
    [java] id numeric(19,0) identity not null,
    [java] name varchar(255) null,
    [java] parent_id numeric(19,0) null,
    [java] primary key (id)
    [java] )
    [java] 09:12:56,779 DEBUG SchemaExport:283 -
    [java] create table Parent (
    [java] id numeric(19,0) identity not null,
    [java] primary key (id)
    [java] )
    [java] 09:12:56,873 DEBUG SchemaExport:283 -
    [java] alter table Child
    [java] add constraint FK3E104FC976A59A
    [java] foreign key (parent_id)
    [java] references Parent
    [java] 09:12:56,952 INFO SchemaExport:200 - schema export complete
    [java] 09:12:56,952 WARN JDBCExceptionReporter:48 - SQL Warning: 5701, SQL
    State: 01000
    [java] 09:12:56,952 WARN JDBCExceptionReporter:49 - [Microsoft][ODBC SQL S
    erver Driver][SQL Server]Changed database context to 'master'.
    [java] 09:12:56,952 WARN JDBCExceptionReporter:48 - SQL Warning: 5703, SQL
    State: 01000
    [java] 09:12:56,952 WARN JDBCExceptionReporter:49 - [Microsoft][ODBC SQL S
    erver Driver][SQL Server]Changed language setting to us_english.
    [java] 09:12:56,983 INFO SessionFactoryImpl:432 - Checking 0 named queries
    [java] Hibernate:
    [java] insert
    [java] into
    [java] Child
    [java] (name)
    [java] values
    [java] (?) select
    [java] scope_identity()
    [java] Hibernate:
    [java] insert
    [java] into
    [java] Child
    [java] (name)
    [java] values
    [java] (?) select
    [java] scope_identity()
    [java] Hibernate:
    [java] insert
    [java] into
    [java] Child
    [java] (name)
    [java] values
    [java] (?) select
    [java] scope_identity()
    [java] Hibernate:
    [java] insert
    [java] into
    [java] Parent
    [java] default
    [java] values
    [java] select
    [java] scope_identity()
    [java] Hibernate:
    [java] update
    [java] Child
    [java] set
    [java] parent_id=?
    [java] where
    [java] id=?
    [java] Hibernate:
    [java] update
    [java] Child
    [java] set
    [java] parent_id=?
    [java] where
    [java] id=?
    [java] Hibernate:
    [java] update
    [java] Child
    [java] set
    [java] parent_id=?
    [java] where
    [java] id=?
    [java] 09:12:57,390 INFO SessionFactoryImpl:831 - closing
    [java] 09:12:57,390 INFO DriverManagerConnectionProvider:147 - cleaning up
    connection pool: jdbc:odbc:MySQL
    BUILD SUCCESSFUL
    Total time: 5 seconds
    Debug level Hibernate log excerpt:
    Included in the above description.

    That's not the right mapping for the 1:m relationship in Hibernate.
    First of all, I believe the recommendation is to have a separate .hbm.xml file for each class, so you should have one for Parent and Child.
    Second, you'll find the proper syntax for a one-to-many relationship here:
    http://www.hibernate.org/hib_docs/v3/reference/en/html/tutorial.html#tutorial-associations
    See if those help.
    The tutorial docs for Hibernate are quite good. I'd recommend going through them carefully.
    %

  • One-to-many relation sometimes INSERTs child before parent

    Hi,
    I have a one-to-many relationship, say Company-Employee, that I want to be
    managed by the parent entity (Company), so that when I make persistent the
    Company, its Employees are also made persistent, and when I delete the
    Company, its Employees are deleted. In my Java code, Company has an
    ArrayList of Employees, and Employee has a Company member variable.
    My metadata looks like this:
    <class name="Company" identity-type="application">...
         <field name="employees">
              <collection element-type="Employee"/>
              <extension vendor-name="kodo" key="inverse-owner" value="company"/>
              <!-- delete all Employees when the Company is deleted -->
              <extension vendor-name="kodo" key="element-dependent" value="true"/>
         </field>
    </class>
    <class name="Employee" identity-type="application">...
         <field name="company"/>
    </class>
    I have a test that is creating a Company with an Employee and persisting
    it. It then deletes the Company. The test is passing some of the time and
    failing some of the time. It seems to not be consistent with the ordering
    of the INSERTs - sometimes it inserts Company then Employee, but sometimes
    it first tries to insert into Employee, which fails with a foreign key
    constraint to the parent table.
    How can I force it to insert into the parent table first?
    I notice that the documentation says you need the field of the child
    entity to be the inverse-owner. Is it not possible for the parent entity
    to own the relationship?
    Many thanks,
    Alex

    Alex,
    If you have non-deferred foreign keys between the tables, and you turn
    on Kodo's foreign key reordering algorithm, Kodo will ensure that all
    your foreign key constraints are met, regardless of the ordering of the
    operations in your Java code.
    See http://docs.solarmetric.com/ref_guide_dbsetup_fks.html for details
    about this.
    Regarding inverse-owner specification -- is there any reason why you
    want to specify this on the other side? inverse-owner basically defines
    which side of a shared relationship defines the mappings and should be
    monitored for changes; it does not have any impact on the mappings
    themselves.
    -Patrick
    Alex Robbins wrote:
    Hi,
    I have a one-to-many relationship, say Company-Employee, that I want to be
    managed by the parent entity (Company), so that when I make persistent the
    Company, its Employees are also made persistent, and when I delete the
    Company, its Employees are deleted. In my Java code, Company has an
    ArrayList of Employees, and Employee has a Company member variable.
    My metadata looks like this:
    <class name="Company" identity-type="application">...
         <field name="employees">
              <collection element-type="Employee"/>
              <extension vendor-name="kodo" key="inverse-owner" value="company"/>
              <!-- delete all Employees when the Company is deleted -->
              <extension vendor-name="kodo" key="element-dependent" value="true"/>
         </field>
    </class>
    <class name="Employee" identity-type="application">...
         <field name="company"/>
    </class>
    I have a test that is creating a Company with an Employee and persisting
    it. It then deletes the Company. The test is passing some of the time and
    failing some of the time. It seems to not be consistent with the ordering
    of the INSERTs - sometimes it inserts Company then Employee, but sometimes
    it first tries to insert into Employee, which fails with a foreign key
    constraint to the parent table.
    How can I force it to insert into the parent table first?
    I notice that the documentation says you need the field of the child
    entity to be the inverse-owner. Is it not possible for the parent entity
    to own the relationship?
    Many thanks,
    Alex

  • One-to-many/foreign keys howto

    I have a situation where I'm trying to assemble a web of data and not make
    JDO mad.
    Here's the structure. I load this data in in batches, with an entry being
    placed in a load history table (H) to track each batch. Each batch
    contains primary (M) records associated with 0..n qualifying records from
    one or both of two auxiliary tables (D, L). All liberally salted with
    primary and foreign keys for referential integrity, and most of the keys
    are compounds, since the "M" identifiers get recycled for each batch load.
    Or, in other words, the "M" key is an ID plus an H key.
    Here's a map:
    H--0..n-->M
    __ +--0..n-->D
    __ +--0..n-->L
    Just to make things even more fun, the primary key of the H table is an
    Oracle 8 "DATE" type, which -- unlike ANSI SQL -- is actually a
    "TIMESTAMP". Kodo is rendering this as a java.util.Date rather than
    java.sql.Date, which is fine, because I need the full millisecond
    resolution. Interestingly, when I altered the schema type to "timestamp",
    load operations failed because the "column value was too big" according to
    Oracle.
    Also adding to the enjoyment, the actual order of presentation of data is
    that ALL M records come in, then ALL D records and finally ALL L records.
    I create my own H when the load starts.
    Now ideally, the whole shooting match will be a single pass/fail
    transaction, but that's for later.
    Right now, I can create the H, no problem and M's no problem. However,
    adding the D's and L's fails come commit time:
    kodo.util.FatalUserException: Attempt to set column "OFAC_ADDRESS.LOAD_ID"
    to two different values: "7/9/04 9:41 AM", "7/9/04 9:41 AM" This can occur
    when you fail to set both sides of a two-sided relation between objects,
    or when you map different fields to the same column, but you do not keep
    the values of these fields in synch.
    The granularity of the timestamps printed isn't making life easier, so I
    double-checked the D record's actual local value
    ADDRESS SERIALIZER A: Fri Jul 09 09:41:58 EDT 2004/Fri Jul 09 09:41:58 EDT
    2004
    ADDRESS SERIALIZER B: 1089380518179/1089380518179 (getTime())
    ADDRESS SERIALIZER C: -1541174818/-1541174818 (hashCode())
    I think I need a clearer understanding of what actions cascade here and
    what actions require manual help. For M, I did a setH(H) plus a
    setHid(H.getId()) and that made it happy. For D's and L's, of course, I
    also have to do a setM(M), where, because of the way the data comes in, I
    had to lookup the previously-stored M based on the M.id plus H.id.
    Now the parent objects contain sets of child objects. In theory, I should
    be adding the newly-created children to those sets, but in practice,
    setting the parent on the child appears to cause this to happen
    automagically, though I still have to manually set the local value of the
    foreign key field.
    I really need to find a good FM to RT. Online (and in the Kodo docs), I
    find a lot about setting up the XML for one-to-many mapping, but the Java
    coding side is taken as obvious. Regrettably, few things are obvious to me.
    I suppose I should excerpt the schema just for completeness:
    <table name="LOAD_HISTORY">
    <pk name="SYS_C0036906" column="LOAD_ID"/>
    <column name="LIST_TYPE" type="varchar" size="32"/>
    <column name="LOADED_BY" type="varchar" size="32"/>
    <column name="LOAD_ID" type="date" not-null="true" size="7"/>
    <column name="SUNSET_TIME" type="date" size="7"/>
    <fk name="FK_LOADHISTORY_LOADEDBY" delete-action="exception"
    to-table="OFAC.OFAC_USERS" column="LOADED_BY"/>
    </table>
    <table name="OFAC_ADDRESS">
    <pk name="SYS_C0036904">
    <on column="ADDRESS_ID"/>
    <on column="LOAD_ID"/>
    </pk>
    <column name="ADDRESS" type="varchar" size="125"/>
    <column name="ADDRESS_ID" type="decimal" not-null="true"
    size="22"/>
    <column name="CITY" type="varchar" size="64"/>
    <column name="COUNTRY" type="varchar" size="64"/>
    <column name="ID" type="decimal" size="22"/>
    <column name="LOAD_ID" type="date" not-null="true" size="7"/>
    <column name="REMARKS" type="varchar" size="300"/>
    <fk name="FK_OFACADDRESS_ID" delete-action="exception"
    to-table="OFAC.OFAC_MAIN">
    <join column="ID" to-column="ID"/>
    <join column="LOAD_ID" to-column="LOAD_ID"/>
    </fk>
    <fk name="FK_OFACADDRESS_LOADID" delete-action="exception"
    to-table="OFAC.LOAD_HISTORY" column="LOAD_ID"/>
    </table>
    <table name="OFAC_ALIAS">
    <pk name="SYS_C0036905">
    <on column="ALIAS_ID"/>
    <on column="LOAD_ID"/>
    </pk>
    <column name="ALIAS" type="varchar" size="200"/>
    <column name="ALIAS_ID" type="decimal" not-null="true"
    size="22"/>
    <column name="ID" type="decimal" size="22"/>
    <column name="LOAD_ID" type="date" not-null="true" size="7"/>
    <column name="REMARKS" type="varchar" size="300"/>
    <fk name="FK_OFACALIAS_ID" delete-action="exception"
    to-table="OFAC.OFAC_MAIN">
    <join column="ID" to-column="ID"/>
    <join column="LOAD_ID" to-column="LOAD_ID"/>
    </fk>
    <fk name="FK_OFACALIAS_LOADID" delete-action="exception"
    to-table="OFAC.LOAD_HISTORY" column="LOAD_ID"/>
    </table>
    <table name="OFAC_MAIN">
    <pk name="SYS_C0036903">
    <on column="ID"/>
    <on column="LOAD_ID"/>
    </pk>
    <column name="ID" type="decimal" not-null="true" size="22"/>
    <column name="LOAD_ID" type="date" not-null="true" size="7"/>
    <column name="REMARKS" type="varchar" size="300"/>
    <fk name="FK_OFACMAIN_LOADID" delete-action="exception"
    to-table="OFAC.LOAD_HISTORY" column="LOAD_ID"/>
    </table>

    Hi Greg,
    I'm just using the unmodified schema-to-mapping output. The one thing that
    might be unusual is that I've broken up related tables into discrete
    packages, but I believe all the items in question are in this package.
    Here it is:
    <?xml version="1.0" encoding="UTF-8"?>
    <mapping>
    <package name="com.everbank.finance.ofac3.jdo.sdn">
    <class name="LoadHistory">
    <jdbc-class-map type="base" table="OFAC.LOAD_HISTORY"/>
    <jdbc-version-ind type="state-image"/>
    <field name="listType">
    <jdbc-field-map type="value" column="LIST_TYPE"/>
    </field>
    <field name="loadId">
    <jdbc-field-map type="value" column="LOAD_ID"/>
    </field>
    <field name="ofacAddress">
    <jdbc-field-map type="one-many"
    ref-column.LOAD_ID="LOAD_ID" table="OFAC.OFAC_ADDRESS"/>
    </field>
    <field name="ofacAlias">
    <jdbc-field-map type="one-many"
    ref-column.LOAD_ID="LOAD_ID" table="OFAC.OFAC_ALIAS"/>
    </field>
    <field name="ofacMains">
    <jdbc-field-map type="one-many"
    ref-column.LOAD_ID="LOAD_ID" table="OFAC.OFAC_MAIN"/>
    </field>
    <field name="ofacUsers">
    <jdbc-field-map type="one-one" column.USER_ID="LOADED_BY"/>
    </field>
    <field name="runInfoLoadIdents">
    <jdbc-field-map type="one-many"
    ref-column.LOAD_ID="LOAD_ID" table="OFAC.RUN_INFO_LOAD_ID"/>
    </field>
    <field name="sunsetTime">
    <jdbc-field-map type="value" column="SUNSET_TIME"/>
    </field>
    </class>
    <class name="OfacAddress">
    <jdbc-class-map type="base" table="OFAC.OFAC_ADDRESS"/>
    <jdbc-version-ind type="state-image"/>
    <field name="address">
    <jdbc-field-map type="value" column="ADDRESS"/>
    </field>
    <field name="addressId">
    <jdbc-field-map type="value" column="ADDRESS_ID"/>
    </field>
    <field name="addressMp1">
    <jdbc-field-map type="value" column="ADDRESS_MP1"/>
    </field>
    <field name="addressMp2">
    <jdbc-field-map type="value" column="ADDRESS_MP2"/>
    </field>
    <field name="city">
    <jdbc-field-map type="value" column="CITY"/>
    </field>
    <field name="cityMp1">
    <jdbc-field-map type="value" column="CITY_MP1"/>
    </field>
    <field name="cityMp2">
    <jdbc-field-map type="value" column="CITY_MP2"/>
    </field>
    <field name="country">
    <jdbc-field-map type="value" column="COUNTRY"/>
    </field>
    <field name="countryMp1">
    <jdbc-field-map type="value" column="COUNTRY_MP1"/>
    </field>
    <field name="countryMp2">
    <jdbc-field-map type="value" column="COUNTRY_MP2"/>
    </field>
    <field name="loadHistory">
    <jdbc-field-map type="one-one" column.LOAD_ID="LOAD_ID"/>
    </field>
    <field name="loadId">
    <jdbc-field-map type="value" column="LOAD_ID"/>
    </field>
    <field name="ofacMain">
    <jdbc-field-map type="one-one" column.ID="ID"
    column.LOAD_ID="LOAD_ID"/>
    </field>
    <field name="remarks">
    <jdbc-field-map type="value" column="REMARKS"/>
    </field>
    </class>
    <class name="OfacAlias">
    <jdbc-class-map type="base" table="OFAC.OFAC_ALIAS"/>
    <jdbc-version-ind type="state-image"/>
    <field name="alias">
    <jdbc-field-map type="value" column="ALIAS"/>
    </field>
    <field name="aliasId">
    <jdbc-field-map type="value" column="ALIAS_ID"/>
    </field>
    <field name="aliasMp1">
    <jdbc-field-map type="value" column="ALIAS_MP1"/>
    </field>
    <field name="aliasMp2">
    <jdbc-field-map type="value" column="ALIAS_MP2"/>
    </field>
    <field name="aliasType">
    <jdbc-field-map type="value" column="ALIAS_TYPE"/>
    </field>
    <field name="loadHistory">
    <jdbc-field-map type="one-one" column.LOAD_ID="LOAD_ID"/>
    </field>
    <field name="loadId">
    <jdbc-field-map type="value" column="LOAD_ID"/>
    </field>
    <field name="ofacMain">
    <jdbc-field-map type="one-one" column.ID="ID"
    column.LOAD_ID="LOAD_ID"/>
    </field>
    <field name="remarks">
    <jdbc-field-map type="value" column="REMARKS"/>
    </field>
    </class>
    <class name="OfacMain">
    <jdbc-class-map type="base" table="OFAC.OFAC_MAIN"/>
    <jdbc-version-ind type="state-image"/>
    <field name="callSign">
    <jdbc-field-map type="value" column="CALL_SIGN"/>
    </field>
    <field name="callSignMp1">
    <jdbc-field-map type="value" column="CALL_SIGN_MP1"/>
    </field>
    <field name="callSignMp2">
    <jdbc-field-map type="value" column="CALL_SIGN_MP2"/>
    </field>
    <field name="grt">
    <jdbc-field-map type="value" column="GRT"/>
    </field>
    <field name="id">
    <jdbc-field-map type="value" column="ID"/>
    </field>
    <field name="loadHistory">
    <jdbc-field-map type="one-one" column.LOAD_ID="LOAD_ID"/>
    </field>
    <field name="loadId">
    <jdbc-field-map type="value" column="LOAD_ID"/>
    </field>
    <field name="matchInfos">
    <jdbc-field-map type="one-many" ref-column.ID="ID"
    ref-column.LOAD_ID="LOAD_ID" table="OFAC.MATCH_INFO"/>
    </field>
    <field name="ofacAddress">
    <jdbc-field-map type="one-many" ref-column.ID="ID"
    ref-column.LOAD_ID="LOAD_ID" table="OFAC.OFAC_ADDRESS"/>
    </field>
    <field name="ofacAlias">
    <jdbc-field-map type="one-many" ref-column.ID="ID"
    ref-column.LOAD_ID="LOAD_ID" table="OFAC.OFAC_ALIAS"/>
    </field>
    <field name="pName">
    <jdbc-field-map type="value" column="P_NAME"/>
    </field>
    <field name="pNameMp1">
    <jdbc-field-map type="value" column="P_NAME_MP1"/>
    </field>
    <field name="pNameMp2">
    <jdbc-field-map type="value" column="P_NAME_MP2"/>
    </field>
    <field name="program">
    <jdbc-field-map type="value" column="PROGRAM"/>
    </field>
    <field name="remarks">
    <jdbc-field-map type="value" column="REMARKS"/>
    </field>
    <field name="sName">
    <jdbc-field-map type="value" column="S_NAME"/>
    </field>
    <field name="sNameMp1">
    <jdbc-field-map type="value" column="S_NAME_MP1"/>
    </field>
    <field name="sNameMp2">
    <jdbc-field-map type="value" column="S_NAME_MP2"/>
    </field>
    <field name="sdnType">
    <jdbc-field-map type="value" column="SDN_TYPE"/>
    </field>
    <field name="ssn">
    <jdbc-field-map type="value" column="SSN"/>
    </field>
    <field name="title">
    <jdbc-field-map type="value" column="TITLE"/>
    </field>
    <field name="tonnage">
    <jdbc-field-map type="value" column="TONNAGE"/>
    </field>
    <field name="vesselFlag">
    <jdbc-field-map type="value" column="VESSEL_FLAG"/>
    </field>
    <field name="vesselOwner">
    <jdbc-field-map type="value" column="VESSEL_OWNER"/>
    </field>
    <field name="vesselOwnerMp1">
    <jdbc-field-map type="value" column="VESSEL_OWNER_MP1"/>
    </field>
    <field name="vesselOwnerMp2">
    <jdbc-field-map type="value" column="VESSEL_OWNER_MP2"/>
    </field>
    <field name="vesselType">
    <jdbc-field-map type="value" column="VESSEL_TYPE"/>
    </field>
    </class>
    </package>
    </mapping>
    Als, just for giggles, the JDO file
    <?xml version="1.0" encoding="UTF-8"?>
    <jdo>
    <package name="com.everbank.finance.ofac3.jdo.sdn">
    <class name="LoadHistory"
    objectid-class="com.everbank.finance.ofac3.jdo.LoadHistoryId">
    <field name="loadId" primary-key="true"/>
    <field name="ofacAddress">
    <collection element-type="OfacAddress"/>
    <extension vendor-name="kodo" key="inverse-owner"
    value="loadHistory"/>
    </field>
    <field name="ofacAlias">
    <collection element-type="OfacAlias"/>
    <extension vendor-name="kodo" key="inverse-owner"
    value="loadHistory"/>
    </field>
    <field name="ofacMains">
    <collection element-type="OfacMain"/>
    <extension vendor-name="kodo" key="inverse-owner"
    value="loadHistory"/>
    </field>
    <field name="runInfoLoadIdents">
    <collection
    element-type="com.everbank.finance.ofac3.jdo.match.RunInfoLoadIdent"/>
    <extension vendor-name="kodo" key="inverse-owner"
    value="loadHistory"/>
    </field>
    </class>
    <class name="OfacAddress"
    objectid-class="com.everbank.finance.ofac3.jdo.OfacAddressId">
    <field name="addressId" primary-key="true"/>
    <field name="loadId" primary-key="true"/>
    </class>
    <class name="OfacAlias"
    objectid-class="com.everbank.finance.ofac3.jdo.OfacAliasId">
    <field name="aliasId" primary-key="true"/>
    <field name="loadId" primary-key="true"/>
    </class>
    <class name="OfacMain"
    objectid-class="com.everbank.finance.ofac3.jdo.OfacMainId">
    <field name="id" primary-key="true"/>
    <field name="loadId" primary-key="true"/>
    <field name="matchInfos">
    <collection
    element-type="com.everbank.finance.ofac3.jdo.match.MatchInfo"/>
    <extension vendor-name="kodo" key="inverse-owner"
    value="ofacMain"/>
    </field>
    <field name="ofacAddress">
    <collection element-type="OfacAddress"/>
    <extension vendor-name="kodo" key="inverse-owner"
    value="ofacMain"/>
    </field>
    <field name="ofacAlias">
    <collection element-type="OfacAlias"/>
    <extension vendor-name="kodo" key="inverse-owner"
    value="ofacMain"/>
    </field>
    </class>
    </package>
    Greg Campbell wrote:
    Hi Tim,
    Could you send the your mapping information corresponding to the class that
    maps to table: OFAC_ADDRESS. In particular, I'm looking for what fields
    map to OFAC_ADDRESS.LOAD_ID. This will hopefully give us a hint as to
    what's going wrong.
    Thanks,
    Greg
    "Tim Holloway" <[email protected]> wrote in message
    news:[email protected]...
    I have a situation where I'm trying to assemble a web of data and not make
    JDO mad.
    <snipped>

  • Need help mapping one-to-many relationship

    [Sorry, inadvertently cross-posted]
    Hello,
    I have a one-to-many mapping question that's probably a no-brainer for the
    experts of the group out there. My problem is that I can't get a collection
    of Items for a given Theme to be populated and I don't know if it's a
    problem in my system.jdo or in my classes (or both). For example, for Theme
    10,
    I want a collection of two Items, item_ids 1 and 2.
    I have db tables named ITEM and THEME with the following layouts:
    ITEM
    |==========================================================|
    | item_id(pk) | item_name | item_number | theme_id(fk) |
    |==========================================================|
    | 1 | This is Item1 | 1234 | 10 |
    | 2 | This is Item2 | 2954 | 10 |
    | 3 | This is Item3 | 2094 | 17 |
    | 4 | This is Item4 | 946 | 11 |
    | ... |
    |==========================================================|
    THEME
    |=======================================|
    | theme_id(pk) | theme_description |
    |=======================================|
    | 4 | Space |
    | 10 | Town |
    | 11 | Train |
    | 17 | Pirate |
    | ... |
    |=======================================|
    I have two PersistenceCapable classes that map to the above tables:
    package com.lego.data;
    public class Item
    public int item_id;
    private String item_number;
    private String item_name;
    private int theme_id;
    public Theme theme;
    public String toString()
    return
    item_number+":"+item_name+":"+theme.getCode()+":"+theme.getDescription();
    package com.lego.data;
    import java.util.*;
    public class Theme
    public int theme_id;
    public String theme_description;
    public Collection items;
    public String toString()
    return theme_id+":"+theme_description;
    and here is my system.jdo file:
    <?xml version = "1.0" encoding = "US-ASCII"?>
    <jdo>
    <package name="com.lego.data">
    <class name="Item" identity-type="application"
    objectid-class="com.lego.data.IntOId">
    <extension vendor-name="kodo" key="table" value="item"/>
    <extension vendor-name="kodo" key="lock-column" value="none"/>
    <extension vendor-name="kodo" key="class-column" value="none"/>
    <field name="item_id" primary-key="true">
    <extension vendor-name="kodo" key="data-column" value="item_id"/>
    </field>
    <field name="item_number">
    <extension vendor-name="kodo" key="data-column" value="item_number"/>
    </field>
    <field name="item_name">
    <extension vendor-name="kodo" key="data-column" value="item_name"/>
    </field>
    <field name="theme_id">
    <extension vendor-name="kodo" key="data-column" value="theme_id"/>
    </field>
    <field name="theme">
    <extension vendor-name="kodo" key="theme_id-data-column"
    value="theme_id"/>
    </field>
    </class>
    <class name="Theme" identity-type="application"
    objectid-class="com.lego.data.ThemeKey">
    <extension vendor-name="kodo" key="table" value="theme"/>
    <extension vendor-name="kodo" key="lock-column" value="none"/>
    <extension vendor-name="kodo" key="class-column" value="none"/>
    <field name="theme_id" primary-key="true">
    <extension vendor-name="kodo" key="data-column" value="theme_id"/>
    </field>
    <field name="theme_description">
    <extension vendor-name="kodo" key="data-column"
    value="theme_description"/>
    </field>
    <field name="items">
    <collection element-type="Item"/>
    <extension vendor-name="kodo" key="inverse" value="theme"/>
    </field>
    </class>
    </package>
    </jdo>
    Thanks in advance for the help.
    -Tim

    Abe White wrote:
    The first thing to check is that you are always setting the "theme" field in
    your Items. If you add an Item i to the "themes" collection of a Theme t, but
    forget to also set i's "theme" field to t, then the change will never get
    written to the database.
    Next, make sure that whenever you set the "theme" field of an Item, you also
    set
    its "theme_id" field. You map both of these fields to the same column, so you
    better be sure they stay in synch.
    On a related note, you might try making the "theme_id" field non-persistent if
    things still aren't working for you. Mapping two fields to the same column
    might be causing trouble. It would be safer to make theme_id non-persistent
    anyway, and to always grab the id from the Theme stored in your "theme"
    field.
    Better OO programming and all that, though I can see that you might have
    performance issues in mind when doing it your way.
    Anyway, if you find that it works when you make theme_id nonpersistent, let us
    know and we'll see why the double-mapping of the column is causing problems,
    and hopefully find a fix.Abe,
    Thanks for the response but I'm still confused. I failed to mention that
    the Item and Theme tables are in an existing schema, so as you saw in my
    system.jdo, I am specifying application identity.
    Since this is an existing schema, the Item table has theme_id as the
    foreign key to the Theme table. So are saying that it is a problem to map
    the both theme_id as a data column and a Theme object in the Item at the
    same time?
    I guess what I don't understand is exactly what my system.jdo should look
    like to map a one-to-many relationship. In my case, from Theme (1) to Item
    (many). (See my system.jdo in previous post).
    Thanks
    -Tim

  • One to Many table join -- concat field per record grouped by id

    Post Author: wm5
    CA Forum: Formula
    Hello,
    I am using Crystal Reports XI and have two tables that have a one to many relationship and are joined by an JobID (number).
    Below is a sample with relative fields for each table.
    job_table: JobID (number), Manager (text), Status (text)
    jobaudit_table : JobAuditID (number), JobID (Number), FormID (Number)
    There is a one to many relationship with jobaudit_table having multiple records for each JobID in job_table.
    I have created a Group Header using the job_table.JobID and suppressed the detail section.
    In the group header for each JobID I display the JobID, Manager, Status. I also use the below formula to determine if any records in the jobaudit_table has a record where FormID = 90. If so, I display "Yes". If not, "No".
    So my report currently looks like.
    JobID     Manager     Status     Audit Performed
    1           Manager 1  Closed           N
    2          Manager 2   Closed           Y
    Here are the formula's I use to determine if any records in jobaudit_table contains a record where FormID = 90.
    @ja90exists
    if {jobaudit_table.FormID} = 90 then    1else    0;
    if sum({@ja90exists},{job_table.JobID}) = 0 then    "No"else    "Yes";
    Everything so far works fine. What I would like to do now is add a hyperlink to a script to view the job audit when in the above report the "Audit Performed" column is "Yes"
    So Report is now:
    JobID     Manager     Status     Audit Performed
    1           Manager 1  Closed           N
    2          Manager 2   Closed           Y (hyperlink to view audit)
    I cannot figure out how to gather the valid JobAuditIDs where FormID = 90 grouped by JobID to be used in the Group Heading section of the report.
    Also, it is unlikely, but possible that more than one job_audit record exists with FormID = 90 per JobID. So, my hyperlink could look like http://mysite.com/viewjobaudit.aspx?jobid=[jobaudit_table.JobAuditID],[jobaudit_table.JobAuditID] .
    Thanks for any help. And if this post is not clear let me know and I will clarify.
    wm5

    Post Author: bettername
    CA Forum: Formula
    Although I can't think of a way to get multiple hyperlinks, this should be a start.  It (should) hyperlink to the last job/audit in the group that formID of 90.  Oh, I assumed that the hyperlink should have been  xxxx...jobID,jobAuditID! 
    I think there may be a way of getting hyperlinks to every "90" record, but that will involve a subreport, so lets try this first...
    1 - everything from your group header to the group footer...
    2 -  add a formula into the group header that says:
    whileprintingrecords;
    stringvar jobauditID="";
    stringvar jobID:=";
    3 - Then add a formula to the details section:
    whileprintingrecords;
    stringvar jobauditID;
    stringvar jobID;
    if {jobaudit_table.FormID} = 90
    then (jobID:=totext({job_table.job_id},0,""); jobauditID:=totext({jobaudit_table.jobaudit_id},0,"")
    4 - Finally, on your "Audit Performed" formula, have a conditional hyperlink that says:
    whileprintingrecords;
    stringvar jobauditID;
    stringvar jobID;
    if {@audit performed} = "Y" then http://mysite.com/viewjobaudit.aspx?jobid=jobID","+jobauditID

Maybe you are looking for

  • Unlocking cores 990xa-gd55

    I have finally worked through my display driver problems (turned out to be a flash problem) now I want to figure out why unlocking the cores works on occasion but most of the time it doesn't.  On the occasion it does unlock all six cores the system r

  • How do I switch Travel Time in Mac Calendar from work to home?

    I recently installed Mavericks and have been using the new Travel Time feature in Calendar.  Today I ran into a problem, however.  I scheduled an appointment and put in the location address.  When I went to enter the travel time, it only gave me two

  • Alternative for Inner Join

    Hi all, Im extracting different fields from material master data into different internal tables. I need to have all the data in these internal table in one final internal table, I don't want to use inner join to get the data into the final internal t

  • HP LJ P2015 ERROR: limitcheck OC: image

    We have an HP LaserJet network printer which is accessed by several devices, principally a MacBook running OSX 10.7 and a MacPro running 10.6. Both computers have problems but they are different. It may be confusing but I will try to address them all

  • IMovie locks/crashes when using firewire for camera and disk

    I've been archiving all my old movies from my Mini-DV camera. My setup is as follows: Mac OSX 10.5.6 and iLive '09 (latest updates), Intel Mac Mini (2008 version), MiniStack external Sata drive, and Canon ZR-60 (firewire). I have the camera hooked in