One-many relation

I have two classes like this:
class A
private Collection classBs;
class B
If I want the relation for classBs field to be one-many how do I state
that in my .JDO file?
Best regards,
/Jan

What version of Kodo are you using?

Similar Messages

  • FatalUserException / One-Many relation relinking

    Hello all,
    I have a problem with one-many relations and relinking... Let's have a
    relation one-many between class Task and itself (classic parent-children
    problem).
    Initial Context
    - T1 has 2 child (T2, T3)
    What i need to do : move T3 as child of T2 to have :
    - T1 has 1 child (T2)
    - T2 has one child (T3)
    How i do it (using a global transaction) :
    transaction.begin();
    // unlinking T3 from T1
    T1.parent = null;
    T3.getChildren().remove(T1)
    // relink T3 to T2
    T1.parent = T2;
    T2.getChildren().add(T1);
    transaction.commit();
    I get this exception :
    Attempt to set column "TASK.parent" to two different values: (class
    java.lang.String)"T2", (null)"null" 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.
    When i test without a global transaction like this :
    transaction.begin();
    // unlinking T3 from T1
    T1.parent = null;
    T3.getChildren().remove(T1)
    transaction.commit();
    transaction.begin();
    // relink T3 to T2
    T1.parent = T2;
    T2.getChildren().add(T1);
    transaction.commit();
    With atomic transaction, everything is always fine. My problem is that I
    need to use global transaction because I need a global rollback and only
    one commit per big process, so I can't use atomic transactions (atomic
    commits takes too much time comparing to a global one) as this :
    Here we're in a particular case where I need to relink a task from a
    parent to its brother. In cases where new parent and old one have no
    close links, global transactions work fine, so this exception is not
    always thrown, which seems pretty weird to me.
    Working case using global transaction :
    =====================
    a) initial context
    T1 have 1 child(T2)
    T3 have 0 child
    b) actions
    moving T2 to T3 with global transaction
    c) result
    T1 have 0 child
    T3 have 1 child(T2)
    =====================
    This is very problematic and strange to me, so any help is welcomed...
    Thomas

    Looks like you use parent/children relationsheep wrongly. Try this instead:
    transaction.begin();
    // unlinking T3 from T1
    //T1.parent = null;
    T1.getChildren().remove(T3)
    // relink T3 to T2
    //T1.parent = T2;
    T3.parent = T2;
    T2.getChildren().add(T3);
    transaction.commit();
    "Thomas cornet" <[email protected]> wrote in message
    news:[email protected]...
    Hello all,
    I have a problem with one-many relations and relinking... Let's have a
    relation one-many between class Task and itself (classic parent-children
    problem).
    Initial Context
    - T1 has 2 child (T2, T3)
    What i need to do : move T3 as child of T2 to have :
    - T1 has 1 child (T2)
    - T2 has one child (T3)
    How i do it (using a global transaction) :
    transaction.begin();
    // unlinking T3 from T1
    T1.parent = null;
    T3.getChildren().remove(T1)
    // relink T3 to T2
    T1.parent = T2;
    T2.getChildren().add(T1);
    transaction.commit();
    I get this exception :
    Attempt to set column "TASK.parent" to two different values: (class
    java.lang.String)"T2", (null)"null" 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.
    When i test without a global transaction like this :
    transaction.begin();
    // unlinking T3 from T1
    T1.parent = null;
    T3.getChildren().remove(T1)
    transaction.commit();
    transaction.begin();
    // relink T3 to T2
    T1.parent = T2;
    T2.getChildren().add(T1);
    transaction.commit();
    With atomic transaction, everything is always fine. My problem is that I
    need to use global transaction because I need a global rollback and only
    one commit per big process, so I can't use atomic transactions (atomic
    commits takes too much time comparing to a global one) as this :
    Here we're in a particular case where I need to relink a task from a
    parent to its brother. In cases where new parent and old one have no
    close links, global transactions work fine, so this exception is not
    always thrown, which seems pretty weird to me.
    Working case using global transaction :
    =====================
    a) initial context
    T1 have 1 child(T2)
    T3 have 0 child
    b) actions
    moving T2 to T3 with global transaction
    c) result
    T1 have 0 child
    T3 have 1 child(T2)
    =====================
    This is very problematic and strange to me, so any help is welcomed...
    Thomas

  • One-many relation - search

    i've 3 tables:
    employees:
    eid,name,dept
    depts:
    did,name,company
    companys:
    cid,name
    the relations are all one-many.
    how can i make a form where i can search all employees of a selected company? or all employees of a selected department.
    only searching by dept is no problem, but the combination of both.....

    you may create your own search dialog box containing the fields to be searched--just like the MS Access application. then you may do all the combination of search, e.g., you may input ename, to find how many depts he/she works, and how many dependents he/she has.

  • MappingInfoNotFoundException with one-many mapping to horizontal PC subclass

    Hi,
    I have a nasty niggling problem with a one-many mapping where the many
    side is a horizontally-mapped persistent subclass:
    kodo.util.FatalUserException: kodo.jdbc.meta.MappingInfoNotFoundException:
    The reference mappings for one-to-many field "Invoice.openTrades" are not
    in the table of the field's related persistent element
    type.[Invoice.openTrades [kodo.jdbc.meta.OneToManyFieldMapping]]
         at
    kodo.runtime.PersistenceManagerImpl.attach(PersistenceManagerImpl.java:4363)...
    NestedThrowablesStackTrace:
    kodo.jdbc.meta.MappingInfoNotFoundException: The reference mappings for
    one-to-many field "Invoice.openTrades" are not in the table of the field's
    related persistent element type.[Invoice.openTrades
    [kodo.jdbc.meta.OneToManyFieldMapping]]
         at kodo.jdbc.meta.Mappings.invalidMapping(Mappings.java:134)
         at kodo.jdbc.meta.Mappings.invalidMapping(Mappings.java:120)
         at
    kodo.jdbc.meta.OneToManyFieldMapping.fromMappingInfo(OneToManyFieldMapping.java:94)
         at
    kodo.jdbc.meta.RuntimeMappingProvider.getFieldMapping(RuntimeMappingProvider.java:198)
         at
    kodo.jdbc.meta.MappingRepository.getFieldMapping(MappingRepository.java:470)
         at
    kodo.jdbc.meta.AbstractClassMapping.getFieldMapping(AbstractClassMapping.java:991)
         at
    kodo.jdbc.meta.AbstractClassMapping.getFieldMapping(AbstractClassMapping.java:971)
         at
    kodo.jdbc.meta.AbstractClassMapping.getMappings(AbstractClassMapping.java:934)
         at
    kodo.jdbc.meta.AbstractClassMapping.getDeclaredFieldMappings(AbstractClassMapping.java:654)
         at
    kodo.jdbc.meta.AbstractClassMapping.resolve(AbstractClassMapping.java:796)
         at kodo.jdbc.meta.MappingRepository.resolve(MappingRepository.java:431)
         at kodo.jdbc.meta.MappingRepository.getMapping(MappingRepository.java:349)
         at kodo.jdbc.meta.MappingRepository.getMapping(MappingRepository.java:177)
         at
    kodo.jdbc.meta.MappingRepository.getMetaData(MappingRepository.java:165)
         at
    kodo.runtime.PersistenceManagerImpl.makePersistent(PersistenceManagerImpl.java:2423)
         at
    kodo.runtime.PersistenceManagerImpl.makePersistent(PersistenceManagerImpl.java:2375)
         at kodo.runtime.AttachManager.makePersistent(AttachManager.java:410)
         at kodo.runtime.AttachManager.attach(AttachManager.java:279)
         at kodo.runtime.AttachManager.attach(AttachManager.java:56)
         at
    kodo.runtime.PersistenceManagerImpl.attach(PersistenceManagerImpl.java:4349)
    I have another one-many mapping on the "one" class which is fine and is
    almost identical to the invalid mapping - it joins on the same
    columns/foreign key. The only real difference is that my invalid "many"
    side is a horizontally mapped subclass (parent class mapped to different
    table). When I took that class out of its hierarchy and mapped it as base,
    it works. I don't know why Kodo is saying the mapping for the join is not
    found, as the "many" side has an invoice field mapped as one-one. The
    superclass does not have a relation to invoice mapped. A slight
    complication is that Invoice itself has a persistent superclass persisted
    in the same table, but nothing refers to that so I don't think it is
    relevant.
    Class diagram is roughly like this:
    BaseTrade
    |
    Invoice 1-* Trade
    BaseReceipt
    |
    Invoice 1-* Receipt
    Invoice mapped to Invoice table; Trade mapped to Trade table but its
    superclass mapped to diff BaseTrade table; Receipt and its superclass
    BaseReceipt mapped to Receipt table.
    I saw an earlier posting on the same exception that mentioned "collection
    element-type" - mine is specified as "Trade", ie the subclass.
    Is there any reason why this should not work?
    I can provide you with .jdo and .mapping files if necessary.
    Many thanks,
    Alex

    Alex-
    Can you post your mapping? I just ran a test with a one-many relation to
    a subclass of a horizontally mapped class, and it worked fine.
    FYI, the example mapping I was using was:
    <?xml version="1.0" encoding="UTF-8"?>
    <mapping>
    <package name="horizmany">
    <class name="HorizManyOwner">
    <jdbc-class-map type="base" pk-column="JDOID"
    table="BUG1174OWNER"/>
    <jdbc-version-ind type="version-number"
    column="JDOVERSION"/>
    <jdbc-class-ind type="in-class-name" column="JDOCLASS"/>
    <field name="relation">
    <jdbc-field-map type="one-many"
    ref-column.JDOID="OWNER_JDOID" table="BUG1174RELATIONSUB"/>
    </field>
    </class>
    <class name="HorizManyRelationSub">
    <jdbc-class-map type="base" pk-column="JDOID"
    table="BUG1174RELATIONSUB"/>
    <jdbc-version-ind type="version-number"
    column="JDOVERSION"/>
    <jdbc-class-ind type="in-class-name" column="JDOCLASS"/>
    <field name="horizmany.HorizManyRelationSuper.superString">
    <jdbc-field-map type="value" column="SUPERSTRING"/>
    </field>
    <field name="owner">
    <jdbc-field-map type="one-one"
    column.JDOID="OWNER_JDOID"/>
    </field>
    <field name="subString">
    <jdbc-field-map type="value" column="SUBSTRING0"/>
    </field>
    </class>
    <class name="HorizManyRelationSuper">
    <jdbc-class-map type="horizontal"/>
    </class>
    </package>
    </mapping>
    In article <[email protected]>, Alex Robbins wrote:
    Hi,
    I have a nasty niggling problem with a one-many mapping where the many
    side is a horizontally-mapped persistent subclass:
    kodo.util.FatalUserException: kodo.jdbc.meta.MappingInfoNotFoundException:
    The reference mappings for one-to-many field "Invoice.openTrades" are not
    in the table of the field's related persistent element
    type.[Invoice.openTrades [kodo.jdbc.meta.OneToManyFieldMapping]]
         at
    kodo.runtime.PersistenceManagerImpl.attach(PersistenceManagerImpl.java:4363)...
    NestedThrowablesStackTrace:
    kodo.jdbc.meta.MappingInfoNotFoundException: The reference mappings for
    one-to-many field "Invoice.openTrades" are not in the table of the field's
    related persistent element type.[Invoice.openTrades
    [kodo.jdbc.meta.OneToManyFieldMapping]]
         at kodo.jdbc.meta.Mappings.invalidMapping(Mappings.java:134)
         at kodo.jdbc.meta.Mappings.invalidMapping(Mappings.java:120)
         at
    kodo.jdbc.meta.OneToManyFieldMapping.fromMappingInfo(OneToManyFieldMapping.java:94)
         at
    kodo.jdbc.meta.RuntimeMappingProvider.getFieldMapping(RuntimeMappingProvider.java:198)
         at
    kodo.jdbc.meta.MappingRepository.getFieldMapping(MappingRepository.java:470)
         at
    kodo.jdbc.meta.AbstractClassMapping.getFieldMapping(AbstractClassMapping.java:991)
         at
    kodo.jdbc.meta.AbstractClassMapping.getFieldMapping(AbstractClassMapping.java:971)
         at
    kodo.jdbc.meta.AbstractClassMapping.getMappings(AbstractClassMapping.java:934)
         at
    kodo.jdbc.meta.AbstractClassMapping.getDeclaredFieldMappings(AbstractClassMapping.java:654)
         at
    kodo.jdbc.meta.AbstractClassMapping.resolve(AbstractClassMapping.java:796)
         at kodo.jdbc.meta.MappingRepository.resolve(MappingRepository.java:431)
         at kodo.jdbc.meta.MappingRepository.getMapping(MappingRepository.java:349)
         at kodo.jdbc.meta.MappingRepository.getMapping(MappingRepository.java:177)
         at
    kodo.jdbc.meta.MappingRepository.getMetaData(MappingRepository.java:165)
         at
    kodo.runtime.PersistenceManagerImpl.makePersistent(PersistenceManagerImpl.java:2423)
         at
    kodo.runtime.PersistenceManagerImpl.makePersistent(PersistenceManagerImpl.java:2375)
         at kodo.runtime.AttachManager.makePersistent(AttachManager.java:410)
         at kodo.runtime.AttachManager.attach(AttachManager.java:279)
         at kodo.runtime.AttachManager.attach(AttachManager.java:56)
         at
    kodo.runtime.PersistenceManagerImpl.attach(PersistenceManagerImpl.java:4349)
    I have another one-many mapping on the "one" class which is fine and is
    almost identical to the invalid mapping - it joins on the same
    columns/foreign key. The only real difference is that my invalid "many"
    side is a horizontally mapped subclass (parent class mapped to different
    table). When I took that class out of its hierarchy and mapped it as base,
    it works. I don't know why Kodo is saying the mapping for the join is not
    found, as the "many" side has an invoice field mapped as one-one. The
    superclass does not have a relation to invoice mapped. A slight
    complication is that Invoice itself has a persistent superclass persisted
    in the same table, but nothing refers to that so I don't think it is
    relevant.
    Class diagram is roughly like this:
    BaseTrade
    |
    Invoice 1-* Trade
    BaseReceipt
    |
    Invoice 1-* Receipt
    Invoice mapped to Invoice table; Trade mapped to Trade table but its
    superclass mapped to diff BaseTrade table; Receipt and its superclass
    BaseReceipt mapped to Receipt table.
    I saw an earlier posting on the same exception that mentioned "collection
    element-type" - mine is specified as "Trade", ie the subclass.
    Is there any reason why this should not work?
    I can provide you with .jdo and .mapping files if necessary.
    Many thanks,
    Alex
    Marc Prud'hommeaux
    SolarMetric Inc.

  • 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'>

  • Relation: one - many / findAllEntries()

    Hello,
    we created a relation one:many (manufacturer:vehicles).
    Everything works fine except our findAll() method for the vehicles (many - side).
    The problem is that we allways get null as result - what we expect is a collection of our car-entities.
    Do we have to pay attention to something special?
    Thanks for help,
    André

    What version of Kodo are you using?

  • 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.

  • 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

  • Many-to-Many relation sample in ADF

    I have a requirement to implement a screen
    Three tables 1) Users 2) Access 3) Documents
    The Access table contains both the references DocId and UserId and acts as the intersection table.
    Users table is related to Documents through the Access table which acts as the intersection table and vice versa. I need to create a screen gui which will show all the documents a user has. Secondly also show all the users who has permission to a particular document. Is there any sample adf application which implements a simple many-to-many relation.
    I am planning to create three entity objects - UsersEO, AccessEO, DocumentsEO
    two view objects - UsersVO and DocumentsVO
    one view link -UsersDocumentVL
    Also which GUI components is best suited to address this. How many Entity Objects, View Objects and View Link should I create. Any simple sampe will help.
    Regards
    Thomas

    Thomas,
    There are of course many ways to implement your requirement. Try this exercise... forget about ADF for a moment; put your computer away (well, finish reading this first ;) ). Grab a pencil and paper.. assuming you could do anything, how would you like the screen to work? Draw it out on a piece of paper and describe how it works. You've just created a rudimentary specification. Now, come back to this thread and describe your specification - perhaps then we can help you implement your spec using ADF (or at least tell you "not possible" and describe why).
    Best,
    John

  • Problem in mapping a many to many relation to a list

    Hi,
    I have a problem with mapping a many to many relation to a list.
    I have a Many to Many relation in my database between tables baskets and products. This relation is implemented with a join table basket_products, which has two fields which correspond to the foreign keys to tables baskets and products. The join table need to have another one column "order", which defines the order of the products for the specific basket.
    In my mapping I have:
    @Entity
    @Table(name = "baskets", uniqueConstraints = {})
    public class Components implements java.io.Serializable {
    @ManyToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)
         @JoinTable( name="baskets_products",
                             joinColumns=@JoinColumn(name="b_id", referencedColumnName="pr_id"),
                             inverseJoinColumns=@JoinColumn(name="pr_id", referencedColumnName="pr_id"))
            //This of course doesn't work!!
           //@OrderBy(value="order")
         public List<Products> getProductses() {
              return this.productses;
         public void setProductses(
                   List<Products> productses) {
              this.productses = productses;
    @Entity
    @Table(name = "products", uniqueConstraints = { })
    public class Products implements java.io.Serializable {
    @ManyToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, mappedBy = "productses")
         public Set<Baskets> getBasketses() {
              return this.basketses;
         public void setBasketses(Set<Basket> basketses) {
              this.basketses = basketses;
         }In the EJB spec I read that :
    "The property or field name must correspond to that of a persistent property or field of the associated
    class."
    What to do if I want to use a field from the join table to do the ordering of the list??
    My problem is that the field "order", is not defined to the EJB container as a persistent field, so it cannot be used. But for my needs it is necessary that this field is included in the join table.
    I thought that I could use the secondary table annotation to map the join table to the Baskets class, as well, so that I can define the order field, but this solution seems to me as a really wrong one.
    Can anyone help me??
    Thanks,
    Elenh.

    Hi Martin-
    Can you please help me. Here are the details:
    We have created an AQ in Oracle DB which will have the following message Structure:
    CREATE OR REPLACE TYPE enqueue_payload AS OBJECT
    ( field1 VARCHAR2(100),
    field2 VARCHAR2(100),
    field3 DATE,
    field4 VARCHAR2(100),
    field5 NUMBER,
    payload CLOB,
    In the Payload field we are enqueing an XML message.
    We have to use a OSB proxy service to dequeue the message from the AQ, transform it to another format and send to a SOA Composite.
    We created a AQ Adapter in Jdeveloper 11g and imported the WSDL, XSD and .jca jca binding file into the OSB project. And configured the OSB proxy service using the WSDL imported.
    However in OSB proxy service message flow when I try to create an XQUERY transformation, I see that the Payload field does not expose the structure of the XML message that is being enqueued. I even changed the message structure definition to have the payload field as XMLType. But it didn't help.
    On analyzing the XSD created by AQ Adapter, I see that the payload is being defined as "string" in the XSD.
    Inputs Needed
    =========
    1. How can we parse the payload field defined as CLOB/XMLType in OSB so that I can see the structure of the XML message it holds ?
    2. Is there any in-built function in OSB to convert it to XML ?
    3. Any other inputs in order to transform the XML message coming in the payload field as CLOB/XMLType
    Please provide your inputs and I hope that I have clearly explained my use case.
    Thanks in advance for your time and help!!
    Regards,
    Dibya

  • Many-Many Relation

    I'm using Sun ONE AS 7 for deploying an EJB jar containing several entitys with relations.
    I can use the methods set<Relation> and I can see the new data in the database system, it looks goods even the tables using for the many-many relations.
    But when I use the get<Relation> method and I try to access the Collection that returns that method I always found the next error:
    WARNING: CORE3283: stderr: java.lang.IllegalStateException
    WARNING: CORE3283: stderr:      at com.sun.jdo.spi.persistence.support.ejb.cmp.E
    JBHashSet.assertInTransaction(EJBHashSet.java:352)
    WARNING: CORE3283: stderr:      at com.sun.jdo.spi.persistence.support.ejb.cmp.E
    JBHashSet.iterator(EJBHashSet.java:295)
    ...I've traced the SQL statement executed by the S1AS and that statement works fine, so the problem is not in the DB system.
    Thanks in advance for your help.

    Hello,
    I got the same problem wit a 1:* Relation, but I can't find an error in my Transactions. All of them are marked as required and I use Container Managed Persistence.
    here is my error code:
    Caught an exception:
    java.lang.IllegalStateException
    at com.sun.jdo.spi.persistence.support.ejb.cmp.EJBHashSet.a
    EJBHashSet.java:339)
    at com.sun.jdo.spi.persistence.support.ejb.cmp.EJBHashSet.s
    t.java:192)
    at util.EmployeeDetails.toString(EmployeeDetails.java:142)
    at clients.TimeRecordClient.main(TimeRecordClient.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Meth
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethod
    java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Delegati
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at com.sun.enterprise.util.Utility.invokeApplicationMain(Ut
    5)
    at com.sun.enterprise.appclient.Main.<init>(Main.java:420)
    at com.sun.enterprise.appclient.Main.main(Main.java:92)
    Maybe someone could help me....

  • Many-to-many relation

    Hi,
    There is a many-to-many relation defined for the following tables:
    Table T_PRICEAFFECTOR
    Name Type
    NAME VARCHAR2(100)
    ISACCUMULATIVE NUMBER(1)
    RATE NUMBER(10,10)
    PRICEAFFECTOR_ID NOT NULL NUMBER(10)
    CATALOG_ID NOT NULL NUMBER(10)
    UNITTYPE NOT NULL NUMBER(1)
    and
    Table T_PRICEAFFECTINGCHAIN
    Name Type
    PRICEAFFECTINGCHAIN_ID NOT NULL NUMBER(10)
    NAME VARCHAR2(100)
    ISDEFAULTFORSTORE NUMBER(1)
    CATALOG_ID NOT NULL NUMBER(10)
    There is also a third table defining the many-to-many relation:
    TABLE T_PRICEAFFECTORTOCHAIN
    Name Type
    PRICEAFFECTOR_ID NOT NULL NUMBER(10)
    PRICEAFFECTINGCHAIN_ID NOT NULL NUMBER(10).
    The classes defined are as follows:
    public class PriceAffectorsChain
         private Catalog catalog;
         private long priceAffectorsChainId;
         private String name;
         private boolean isDefaultForStore;
         private Collection priceAffectors = new HashSet ();
         private Collection products = new HashSet ();
    public class PriceAffector
         private long priceAffectorId;
         private long isAccumulative;
         private String name;
         private double rate;
         private Catalog catalog;
         private int unitType;
         private Collection priceAffectorsChains = new HashSet ();
    and these are defined in the jdo descriptor in the following way:
    <class name="PriceAffector" identity-type="application"
    objectid-class="jp.telewave.platpark.eis.dao.pk.PriceAffectorPK">
         <extension vendor-name="kodo" key="lock-column" value="none"/>
         <extension vendor-name="kodo" key="class-column" value="none"/>
         <extension vendor-name="kodo" key="table" value="T_PRICEAFFECTOR"/>
         <field name="priceAffectorId" primary-key="true">
              <extension vendor-name="kodo" key="data-column"
    value="PRICEAFFECTOR_ID"/>
         </field>
         <field name="isAccumulative">
              <extension vendor-name="kodo" key="data-column" value="ISACCUMULATIVE"/>
         </field>
         <field name="name">
              <extension vendor-name="kodo" key="data-column" value="NAME"/>
         </field>
         <field name="rate">
              <extension vendor-name="kodo" key="data-column" value="RATE"/>
         </field>
         <field name="unitType">
              <extension vendor-name="kodo" key="data-column" value="UNITTYPE"/>
         </field>
         <field name="catalog">
              <extension vendor-name="kodo" key="catalogId-data-column"
    value="CATALOG_ID"/>
         </field>
         <field name="priceAffectorsChains">
              <collection element-type="PriceAffectorsChain"/>
              <extension vendor-name="kodo" key="read-only" value="true"/>
              <extension vendor-name="kodo" key="inverse" value="priceAffectors"/>
              <extension vendor-name="kodo" key="table"
    value="T_PRICEAFFECTORTOCHAIN"/>
              <extension vendor-name="kodo" key="priceAffectorId-ref-column"
    value="PRICEAFFECTOR_ID"/>
              <extension vendor-name="kodo" key="priceAffectorsChainId-data-column"
    value="PRICEAFFECTINGCHAIN_ID"/>
         </field>
    </class>
    <class name="PriceAffectorsChain" identity-type="application"
    objectid-class="jp.telewave.platpark.eis.dao.pk.PriceAffectorsChainPK">
         <extension vendor-name="kodo" key="lock-column" value="none"/>
         <extension vendor-name="kodo" key="class-column" value="none"/>
         <extension vendor-name="kodo" key="table" value="T_PRICEAFFECTINGCHAIN"/>
         <field name="priceAffectorsChainId" primary-key="true">
              <extension vendor-name="kodo" key="data-column"
    value="PRICEAFFECTINGCHAIN_ID"/>
         </field>
    <field name="catalog">
              <extension vendor-name="kodo" key="catalogId-data-column"
    value="CATALOG_ID"/>
         </field>
         <field name="name">
              <extension vendor-name="kodo" key="data-column" value="NAME"/>
         </field>
         <field name="isDefaultForStore">
         <extension vendor-name="kodo" key="data-column"
    value="ISDEFAULTFORSTORE"/>
         </field>
         <field name="priceAffectors">
              <collection element-type="PriceAffector"/>
              <extension vendor-name="kodo" key="read-only" value="false"/>
              <extension vendor-name="kodo" key="inverse"
    value="priceAffectorsChains"/>
              <extension vendor-name="kodo" key="table"
    value="T_PRICEAFFECTORTOCHAIN"/>
              <extension vendor-name="kodo" key="priceAffectorsChainId-ref-column"
    value="PRICEAFFECTINGCHAIN_ID"/>
              <extension vendor-name="kodo" key="priceAffectorId-data-column"
    value="PRICEAFFECTOR_ID"/>
         </field>
         <field name="products">
         <collection element-type="Product"/>
         <extension vendor-name="kodo" key="inverse" value="priceAffectorsChain"/>
         </field>
    </class>
    =============================================================
    Ok. The problem with the mapping is that it works only one way. What I
    mean is that when I try to add new PriceAffectorsChain with many
    PriceAffector objects only the PriceAffectorsChain object is being
    persisted, and none of the PriceAffectors are persisted in the
    many-to-many table (T_PRICEAFFECTORTOCHAIN), even when the read-only
    extensions are set.
    That was not the case when I tried to add new PriceAffector with many
    PriceAfffectorsChain - everything worked.
    Any Ideas?
    -Ivan

    Abe White wrote:
    When you have a two-sided relation, you need to be maintaining both sides
    of the relation at all times. Whenever an A is added to a B, the B must
    be added to the A as well. Keep your in-memory Java objects consistent
    (just as if they were not persistent), and JDO will take care of the rest.Abe White wrote:
    When you have a two-sided relation, you need to be maintaining both sides
    of the relation at all times.
    Whenever an A is added to a B, the B must
    be added to the A as well. Keep your in-memory Java objects consistent
    (just as if they were not persistent), and JDO will take care of the rest.Ok. I agree.
    I think that I'm doing this or maybe I'm wrong. Below is the code that
    adds new price affectors chain with collection of price affectors (all of
    them already persistent). Each of the price affectors is being looked up
    and is consistent (this is what getObjectById is doing, isn't it?) and
    then the price affector chain is being persisted.
    =================================================================
    PersistenceManager pm = null;
    PriceAffectingChain newPriceAffectorsChain = null;
    HashSet priceAffectors = null;
    try {
    pm = persistenceManagerFactory.getPersistenceManager();
    // getting the catalog object
    long catalogId = priceAffectorsChain.getCatalog().getCatalogId();
    CatalogPK catalogPK = new CatalogPK(catalogId);
    Catalog newPriceAffectorsChainCatalog =
    (Catalog)pm.getObjectById(catalogPK, true);
    // making new price affecting chain
    newPriceAffectorsChain = new PriceAffectingChain(
    BeanHelper.getNextSequence(DBObjects.SEQ_PRICEAFFECTINGCHAIN),
    priceAffectorsChain.getName(),
         priceAffectorsChain.getIsDefaultForStore(),
         newPriceAffectorsChainCatalog);
    // retrieval of price affector objects for this chain
    System.out.println("the size of the price affectors is: " +
    priceAffectorPKs.length);
    if (priceAffectorPKs != null && priceAffectorPKs.length > 0) {
         priceAffectors = new HashSet(priceAffectorPKs.length);
    for (int i = 0; i < priceAffectorPKs.length; i++) {
              PriceAffectorPK currentPAPK = priceAffectorPKs;
              PriceAffector currentPA = (PriceAffector)pm.getObjectById(currentPAPK,
    true);
              priceAffectors.add(currentPA);
              System.out.println("The " + currentPA.getName() + " price affector was
    added");
    if (priceAffectors == null) {
         priceAffectors = new HashSet();
    System.out.println("size of priceAffectors: " +
    priceAffectors.size());
    newPriceAffectorsChain.setPriceAffectors(priceAffectors);
    pm.makePersistent(newPriceAffectorsChain);
    } catch {
    ===========================================================
    The problem is that the presistence works only for the table of
    PriceAffectingChain obejct and not for the relation table. I tried on
    purpose to add new price affectors with collection of price affecting
    chains and it worked for both tables (the one for PriceAffector object and
    the relation table.
    I have no idea what I can try next. Any advice or help are welcomed.
    Thanks.
    -Ivan

Maybe you are looking for