Problem inserting one-to-many collection

Hi,
I've been trying to get an object (CMDMessage) that has a one-to-many collection (CMDMessageXREF)
inserted into the database, but no matter what I try I can't seem to get the collection to grab the
foreign key value of 'msg_id' to populate that field in the CMDMessageXREF object, I keep getting a nul value.
From reading the forums, it seems the best way to get this value is to setup a back reference one-to-one mapping from the collection to the parent
object, but this doesn't seem to be working from me.
I've attached the pertinent client code as well as the pertinent information from the descriptors and would
appreciate any help on this.
Thanks,
Mark
Client code:
CMDMessage note = new CMDMessage();
note.setAuthorId(new Double(58402));
note.setMsgSubject("Sequence test2");
java.util.ArrayList xrefCollection = new java.util.ArrayList();
CMDMessageXREF xref = new CMDMessageXREF();
xref.setRecipientId(new Double(58400));
xref.setRecipientType("org");
xrefCollection.add(xref);
note.setCmdMessageXrefCollection(xrefCollection);
// runs transaction     invoking UnitOfWork to insert objects
TransactionEngine.insert(note);
Descriptors:
public Descriptor buildCMDMessageDescriptor() {
     Descriptor descriptor = new Descriptor();
     descriptor.setJavaClass(CMDMessage.class);
     descriptor.addTableName("CMD_MESSAGE");
     descriptor.addPrimaryKeyFieldName("CMD_MESSAGE.MSG_ID");
     // Descriptor properties.
     descriptor.useNoIdentityMap();
     descriptor.setIdentityMapSize(1000);
     descriptor.useRemoteNoIdentityMap();
     descriptor.setRemoteIdentityMapSize(1000);
     descriptor.setSequenceNumberFieldName("CMD_MESSAGE.MSG_ID");
     descriptor.setSequenceNumberName("CMD_MSG_ID_SEQUENCE");
     descriptor.alwaysConformResultsInUnitOfWork();
     descriptor.onlyRefreshCacheIfNewerVersion();
     descriptor.setAlias("CMDMessage");
     // Query manager.
     descriptor.useChangedFieldsLocking();
     descriptor.getQueryManager().checkDatabaseForDoesExist();
     //Named Queries
     // Event manager.
     // Mappings.
     DirectToFieldMapping msgIdMapping = new DirectToFieldMapping();
     msgIdMapping.setAttributeName("msgId");
     msgIdMapping.setGetMethodName("getMsgId");
     msgIdMapping.setSetMethodName("setMsgId");
     msgIdMapping.setFieldName("CMD_MESSAGE.MSG_ID");
     descriptor.addMapping(msgIdMapping);
     DirectToFieldMapping msgSubjectMapping = new DirectToFieldMapping();
     msgSubjectMapping.setAttributeName("msgSubject");
     msgSubjectMapping.setGetMethodName("getMsgSubject");
     msgSubjectMapping.setSetMethodName("setMsgSubject");
     msgSubjectMapping.setFieldName("CMD_MESSAGE.MSG_SUBJECT");
     descriptor.addMapping(msgSubjectMapping);
     OneToManyMapping cmdMessageXrefCollectionMapping = new OneToManyMapping();
     cmdMessageXrefCollectionMapping.setAttributeName("cmdMessageXrefCollection");
     cmdMessageXrefCollectionMapping.setGetMethodName("getCmdMessageXrefCollection");
     cmdMessageXrefCollectionMapping.setSetMethodName("setCmdMessageXrefCollection");
     cmdMessageXrefCollectionMapping.setReferenceClass(CMDMessageXREF.class);
     cmdMessageXrefCollectionMapping.useTransparentCollection();
     cmdMessageXrefCollectionMapping.useCollectionClass(oracle.toplink.indirection.IndirectList.class);
     cmdMessageXrefCollectionMapping.readOnly();
     cmdMessageXrefCollectionMapping.addTargetForeignKeyFieldName("CMD_MESSAGE_XREF.MSG_ID", "CMD_MESSAGE.MSG_ID");
     descriptor.addMapping(cmdMessageXrefCollectionMapping);
     return descriptor;
public Descriptor buildCMDMessageXREFDescriptor() {
     Descriptor descriptor = new Descriptor();
     descriptor.setJavaClass(CMDMessageXREF.class);
     descriptor.addTableName("CMD_MESSAGE_XREF");
     descriptor.addPrimaryKeyFieldName("CMD_MESSAGE_XREF.ID");
     // Descriptor properties.
     descriptor.useNoIdentityMap();
     descriptor.setIdentityMapSize(1000);
     descriptor.useRemoteNoIdentityMap();
     descriptor.setRemoteIdentityMapSize(1000);
     descriptor.setSequenceNumberFieldName("CMD_MESSAGE_XREF.ID");
     descriptor.setSequenceNumberName("CMD_MSG_XREF_ID_SEQ");
     descriptor.alwaysConformResultsInUnitOfWork();
     descriptor.onlyRefreshCacheIfNewerVersion();
     descriptor.setAlias("CMDMessageXREF");
     // Query manager.
     descriptor.useChangedFieldsLocking();
     descriptor.getQueryManager().checkDatabaseForDoesExist();
     //Named Queries
     // Event manager.
     // Mappings.
     DirectToFieldMapping idMapping = new DirectToFieldMapping();
     idMapping.setAttributeName("id");
     idMapping.setGetMethodName("getId");
     idMapping.setSetMethodName("setId");
     idMapping.setFieldName("CMD_MESSAGE_XREF.ID");
     descriptor.addMapping(idMapping);
     DirectToFieldMapping msgIdMapping = new DirectToFieldMapping();
     msgIdMapping.setAttributeName("msgId");
     msgIdMapping.setGetMethodName("getMsgId");
     msgIdMapping.setSetMethodName("setMsgId");
     msgIdMapping.setFieldName("CMD_MESSAGE_XREF.MSG_ID");
     descriptor.addMapping(msgIdMapping);
     DirectToFieldMapping recipientIdMapping = new DirectToFieldMapping();
     recipientIdMapping.setAttributeName("recipientId");
     recipientIdMapping.setGetMethodName("getRecipientId");
     recipientIdMapping.setSetMethodName("setRecipientId");
     recipientIdMapping.setFieldName("CMD_MESSAGE_XREF.RECIPIENT_ID");
     descriptor.addMapping(recipientIdMapping);
     OneToOneMapping cmdMessageInfoMapping = new OneToOneMapping();
     cmdMessageInfoMapping.setAttributeName("cmdMessageInfo");
     cmdMessageInfoMapping.setGetMethodName("getCmdMessageInfoHolder");
     cmdMessageInfoMapping.setSetMethodName("setCmdMessageInfoHolder");
     cmdMessageInfoMapping.setReferenceClass(CMDMessage.class);
     cmdMessageInfoMapping.useBasicIndirection();
     cmdMessageInfoMapping.readOnly();
     cmdMessageInfoMapping.addTargetForeignKeyFieldName("CMD_MESSAGE.MSG_ID", "CMD_MESSAGE_XREF.MSG_ID");
     descriptor.addMapping(cmdMessageInfoMapping);
     return descriptor;
}

Chris,
Ok, I've tried both approaches
1. using direct field mapping, getting rid of the one to one mapping on the CMDMessageXREF object, and adding this line xref.setMsgId( note.getMsgId()
and
2. removing the readOnly line for the mappings and setting the CMDMessage in the CMDMessageXREF object as shown below in bold.
but still am getting the same error. Could this be because the MSG_ID field in the database is NOT NULL? Otherwise, I am not seeing what else I can do differently to set this up. Below is the updated relevant code and descriptor showing the second approach I used.
Thanks for the help,
Mark
Client code
CMDMessage note = new CMDMessage();
note.setAuthorId(new Double(58402));
note.setMsgSubject("Sequence test2");
java.util.ArrayList xrefCollection = new java.util.ArrayList();
CMDMessageXREF xref = new CMDMessageXREF();
xref.setRecipientId(new Double(58400));
// added to set value to valueHolder
xref.setCmdMessageInfo(note);
xrefCollection.add(xref);
note.setCmdMessageXrefCollection(xrefCollection);
TransactionEngine.insert(note);
Descriptors
public Descriptor buildCMDMessageDescriptor() {
     Descriptor descriptor = new Descriptor();
     descriptor.setJavaClass(CMDMessage.class);
     descriptor.addTableName("CMD_MESSAGE");
     descriptor.addPrimaryKeyFieldName("CMD_MESSAGE.MSG_ID");
     // Descriptor properties.
     descriptor.useNoIdentityMap();
     descriptor.setIdentityMapSize(1000);
     descriptor.useRemoteNoIdentityMap();
     descriptor.setRemoteIdentityMapSize(1000);
     descriptor.setSequenceNumberFieldName("CMD_MESSAGE.MSG_ID");
     descriptor.setSequenceNumberName("CMD_MSG_ID_SEQUENCE");
     descriptor.alwaysConformResultsInUnitOfWork();
     descriptor.onlyRefreshCacheIfNewerVersion();
     descriptor.setAlias("CMDMessage");
     // Query manager.
     descriptor.useChangedFieldsLocking();
     descriptor.getQueryManager().checkDatabaseForDoesExist();
     //Named Queries
     // Event manager.
     // Mappings.
     DirectToFieldMapping msgIdMapping = new DirectToFieldMapping();
     msgIdMapping.setAttributeName("msgId");
     msgIdMapping.setGetMethodName("getMsgId");
     msgIdMapping.setSetMethodName("setMsgId");
     msgIdMapping.setFieldName("CMD_MESSAGE.MSG_ID");
     descriptor.addMapping(msgIdMapping);
     OneToManyMapping cmdMessageXrefCollectionMapping = new OneToManyMapping();
     cmdMessageXrefCollectionMapping.setAttributeName("cmdMessageXrefCollection");
     cmdMessageXrefCollectionMapping.setGetMethodName("getCmdMessageXrefCollection");
     cmdMessageXrefCollectionMapping.setSetMethodName("setCmdMessageXrefCollection");
     cmdMessageXrefCollectionMapping.setReferenceClass(CMDMessageXREF.class);
     cmdMessageXrefCollectionMapping.useTransparentCollection();
     cmdMessageXrefCollectionMapping.useCollectionClass(oracle.toplink.indirection.IndirectList.class);
     cmdMessageXrefCollectionMapping.addTargetForeignKeyFieldName("CMD_MESSAGE_XREF.MSG_ID", "CMD_MESSAGE.MSG_ID");
     descriptor.addMapping(cmdMessageXrefCollectionMapping);
     return descriptor;
public Descriptor buildCMDMessageXREFDescriptor() {
     Descriptor descriptor = new Descriptor();
     descriptor.setJavaClass(CMDMessageXREF.class);
     descriptor.addTableName("CMD_MESSAGE_XREF");
     descriptor.addPrimaryKeyFieldName("CMD_MESSAGE_XREF.ID");
     // Descriptor properties.
     descriptor.useNoIdentityMap();
     descriptor.setIdentityMapSize(1000);
     descriptor.useRemoteNoIdentityMap();
     descriptor.setRemoteIdentityMapSize(1000);
     descriptor.setSequenceNumberFieldName("CMD_MESSAGE_XREF.ID");
     descriptor.setSequenceNumberName("CMD_MSG_XREF_ID_SEQ");
     descriptor.alwaysConformResultsInUnitOfWork();
     descriptor.onlyRefreshCacheIfNewerVersion();
     descriptor.setAlias("CMDMessageXREF");
     // Query manager.
     descriptor.useChangedFieldsLocking();
     descriptor.getQueryManager().checkDatabaseForDoesExist();
     //Named Queries
     // Event manager.
     // Mappings.
     DirectToFieldMapping idMapping = new DirectToFieldMapping();
     idMapping.setAttributeName("id");
     idMapping.setGetMethodName("getId");
     idMapping.setSetMethodName("setId");
     idMapping.setFieldName("CMD_MESSAGE_XREF.ID");
     descriptor.addMapping(idMapping);
     DirectToFieldMapping recipientIdMapping = new DirectToFieldMapping();
     recipientIdMapping.setAttributeName("recipientId");
     recipientIdMapping.setGetMethodName("getRecipientId");
     recipientIdMapping.setSetMethodName("setRecipientId");
     recipientIdMapping.setFieldName("CMD_MESSAGE_XREF.RECIPIENT_ID");
     descriptor.addMapping(recipientIdMapping);
     OneToOneMapping cmdMessageInfoMapping = new OneToOneMapping();
     cmdMessageInfoMapping.setAttributeName("cmdMessageInfo");
     cmdMessageInfoMapping.setGetMethodName("getCmdMessageInfoHolder");
     cmdMessageInfoMapping.setSetMethodName("setCmdMessageInfoHolder");
     cmdMessageInfoMapping.setReferenceClass(CMDMessage.class);
     cmdMessageInfoMapping.useBasicIndirection();
     cmdMessageInfoMapping.addTargetForeignKeyFieldName("CMD_MESSAGE.MSG_ID", "CMD_MESSAGE_XREF.MSG_ID");
descriptor.addMapping(cmdMessageInfoMapping);
     return descriptor;
}

Similar Messages

  • 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

  • FK problem when inserting one-to-many records

    Hi everybody,
    I see that this subject has been discussed here from time to time before, as in:
    insert record with 1-M mapping missing foreign key using UOW
    Sequences and multiple tables for inheritance
    I followed Dougs advice on several posts, to check out the employee exampled shipped with Toplink, but regardless of all this information, I'm still stuck.
    So, my issue: when I create new objects, add them to some other objects collection, and then call "assign sequence numbers" on all of them, the sequencenumbers are assgned all the way down the hierachy, but the upward links - the foreign keys - are not updated with the ID's of the parent object.
    Simple example (might not compile - demo code):
    <JAVA>
    myInputController.session = (DatabaseSession)
    SessionManager.getManager().getSession("some_session");
    UnitOfWork myUnitOfWork = myInputController.session.acquireUnitOfWork();
    // Father and Child are a Toplink objects, persisted to each their table with a
    // FK relation, is now assigned to the UOW
    Father myDBFather = (Father) myUnitOfWork.registerObject(new Father());
    Child myDBChild = new Child();
    myDBFather.getChildCollection().add(myDBChild);
    // Now I could use the accessor methods of the Toplink objects to set
    // stuff like name, phone number or so, but that's not important for demo.
    // I just want to save my objects to the database. To do so, I need to
    // assign sequence numbers:
    myUnitOfWork.assignSequenceNumbers();
    // I check the ID's before writing to DB:
    System.out.println(myDBFather.GetId().toString());
    System.out.println(myDBChild.GetId().toString());
    // They both return valid numbers, similar to what the sequence objects
    // of the database should asssign, so that works.
    // But:
    System.out.println(myDBChild.GetFaterid().toString());
    // Will return null, even if myDBChild is a child of myDBFather, and
    // hence a commit to the database will fail (no foreign key!).
    // I can fix this, by "manually" setting the id:
    myDBChild.SetFatherid(myDBFather.getId());
    // And then a commit to the database will work:
    myUnitOfWork.commit();
    // But, since I have deep hierachies, and don't allways know what
    // objects have been added/changed, it's a pretty wild thing, not
    // to menition un-ellegant and heavy in maintenance, to loop down
    // through the entire collection and update all foreign key ID's
    // (FatherID's) before committing changes.
    </JAVA>
    I guess I'm just not hitting the right button somewhere? To create the Toplink Java classes and descriptors, I used "Java objects from tables" in JDev 10.1.2, both "as is", and with some tinkering on indirection, transparency and bi-directional relationships. Also, I get same results in the Toplink 10.1.3 dp4.
    I must have missed the answer somewhere out there, but must post after trying really hard!
    Best regards to all of you,
    :) Ulf

    I could kick myself right now!
    The child setFatherid method takes an entire father object, so the code must be myDBChild.SetFatherid(myDBFather); instead of the myDBChild.SetFatherid(myDBFather.getId()); My apologies.
    With the issue still very present, I post some code from the auto-generated child-class and the child-class descriptor below, which might give some pointers.
    <JAVA-FRAGMENT>
    package dk.test.fatherchild.model;
    import oracle.toplink.indirection.ValueHolder;
    import oracle.toplink.indirection.ValueHolderInterface;
    public class Child {
    * Map fatherid <-> dk.test.fatherchild.model.Father
    * @associates <{dk.test.fatherchild.model.Father}>
         private ValueHolderInterface fatherid;
         private Double childid;
         private String childName;
    public Child() {
         super();
         this.fatherid = new ValueHolder();
    </JAVA-FRAGMENT>
    <Child.ClassDescriptor.xml-FRAGMENT>
    <mapping>
    <inherited>false</inherited>
    <instance-variable-name>fatherid</instance-variable-name>
    <uses-method-accessing>false</uses-method-accessing>
    <read-only>false</read-only>
    <get-method-handle>
    <method-handle empty-aggregate="true"/>
    </get-method-handle>
    <set-method-handle>
    <method-handle empty-aggregate="true"/>
    </set-method-handle>
    <reference-descriptor>dk.test.fatherchild.model.Father.ClassDescriptor</reference-descriptor>
    <private-owned>false</private-owned>
    <uses-batch-reading>false</uses-batch-reading>
    <maintains-bidirectional-relationship>true</maintains-bidirectional-relationship>
    <relationship-partner-mapping-name>childCollection</relationship-partner-mapping-name>
    <table-reference-mapping-reference-handle>
    <reference-handle>
    <reference-table>PERIODICA2.CHILD</reference-table>
    <reference-name>CHILD_FATHER_FK</reference-name>
    </reference-handle>
    </table-reference-mapping-reference-handle>
    <uses-joining>false</uses-joining>
    <one-to-one-mapping-indirection-policy>
    <indirection-policy>
    <uses-indirection>true</uses-indirection>
    </indirection-policy>
    </one-to-one-mapping-indirection-policy>
    <mapping-class>MWOneToOneMapping</mapping-class>
    </mapping>
    </Child.ClassDescriptor.xml-FRAGMENT>

  • EJB 2.0 RI, CMR, problem with one-to-many

    I got an entity bean with a one/many, bidirectional, non-cascading relationship to another entity bean. The "one" side is represented by the remote type of the related entity bean.
    The "many" side is represented by the type "java.util.Collection".
    Unfortunately, the Verifier spits out the following error for the "many" side:
    Error : Invalid type assigned for container managed field [ depots ] in bean [ Account ]
    "depots" is defined in AccountEJB.java via the abstract contract
    [import java.util.Collection;]
    public abstract Collection getDepots();
    public abstract void setDepots(Collection depots);
    Q1. Is there anything wrong with this?
    Q2. Does the currect J2EE RI 1.3 beta support CMR as defined in the draft2 of EJB 2.0?
    Q3. Do I need to mark the CMR fields as CMP 2.0 ("fields to be persisted") in the Deployment Tool? I'd say yes, but if I would be picky, CMR would not be CMP...
    Q4. Can anyone point me to a good example of CMR. The PetStore App uses BMP everywhere, and I could not find any other useful demos.
    I'd appreciate any help!
    Greetings,
    Andreas

    I am new to J2SDKEE1.3 CMR. I have similar question about CMR. The only example is the "customer" under the J2SDKEE1.3 doc fold. Can anyone provide more examples?
    Thanks in Advance.
    Oliver

  • One-to-many relationships problem

    Hi,
    I'm having some problems with one-to-many relationships.
    I've a two way relationship beetwen Person and Document.
    Person has a collection of Documents (1-n).
    Document has an instance for Person.
    In my database schema Document has a FK for person.
    The problem occurs when I'm trying to save the Person object
    with a collection of Documents.
    Oracle gives me the following message:
    ORA-00001: unique constraint (SMS.PK_PERSON) violated
    In my kodo.properties file I put:
    kodo.jdbc.ForeignKeyConstraints: true
    It seems that when the collection of Documents is persisted, kodo tries to
    save a new Person object for each Document.
    When I have just one instance of Document in my collection kodo persists
    it ok, but when I have move instances I get
    that problem.
    Can somebody help me?
    Thanks in advance,
    Joan Caffee

    You need to make sure each Document references the same Person object in
    the JVM. JDO persists your object model as-is. Each distinct JVM
    object becomes a distinct database record. You can't have multiple JVM
    objects in the same PersistenceManager representing the same database
    record.

  • One-to-many with subclasses

    Hello again,
    there seems to be a problem with one-to-many relations involving
    inheritence...
    Let me describe the setting:
    class AbstractUsecase {
    // element-type=Account
    Set accounts;
    class Usecase extends AbstractUsecase {
    class Account extends AbstractAccount implements InstanceCallbacks {
    // element-type=AccountRevisionItem
    List revisions;
    AbstractUsecase uc;
    class AccountRevisionItem extends Account {
    long time;
    User user;
    As you can see a simple model (in uml it looks much more better).
    In the method jdoPreStore() of Account an object of type
    AccountRevisionItem will added to revisions. This new object holds the
    data of Account, the User and timestamp of the modifing. So we are able to
    trace every change on the date (user, date). Metadata looks like this:
    <class name="AbstractUsecase"/>
    <class name="Usecase" persistence-capable-superclass="AbstractUsecase">
    <class name="Abstractaccount"/>
    <class name="Account" persistence-capable-superclass="AbstractAccount">
    <extension vendor-name="kodo" key="table" value="Account"/>
    <field name="revisions">
    <collection element-type="AccountRevisionItem"/>
    </field>
    </class>
    <class name="AccountRevisionItem"
    persistence-capable-superclass="Account"/>
    When i get a extent of all Accounts i can fetch all revisions of each
    Account.
    Now the problem: When i fetch all accounts of a usecase there are objects
    included of type Account AND AccountRevisionItem. The generated SQL code
    shows also why: ...t0.JDOCLASSX IN ('tolina.data.Account',
    'tolina.data.AccountRevisionItem')...
    Kodo tries when fetching a set of Accounts also all subclasses of
    Accounts! How can i say: this set contains only accounts and no fetching
    of subclasses is needed!
    I would be grateful for any help!
    PS: I noticed that kodo deletes all elements of a list when inserting a
    new element, i remember there a several faqs around this. Can you anyway
    give a work-a-round?

    Hi Patrick,
    i found my mistake: in the copy() method of AccountRevisionItem which
    copies the attributes of the Accountobject, i copied the Usecase reference
    too.
    So when all Accounts of a usecase will be fetched the copied
    AccountRevisionItem matched too, because of the fk of the usecase :[
    I was wondering why i get the RevisionItem although i never added it to
    the list of accounts in the usecase - now i know :)
    Your strategy to fetch all objects of the desired class AND subclass when
    traverse a relation is of course right. But can i control it like in the
    case from extents?
    Your proposal to use sets instead of lists is not really the solution,
    because sets have no order of the containing elements!
    I have to life with sets because deleting all elements when inserting a
    new one is not really performant...
    Thanks anyway for your quick help!
    I promise this was not the last time, because we will use kodo in a
    prototyp-project - when it will be a success we will buy kodo.
    Patrick Linskey wrote:
    How are you getting the extent? If you do:
    Extent e = pm.getExtent (Account.class, true);
    you will get all subclasses. If you do:
    Extent e = pm.getExtent (Account.class, false);
    then you will get an extent of just Account objects -- no subclasses.
    Now, if you're traversing a relation, we will always return all objects
    in that relation, regardless of subclass. So, if you have a one-many
    relation from UseCase to Account, we'll return all objects in that
    relation. However, that relation should only contain data that you put
    into it, so if you never put anything but Account objects into it, then
    you should not see anything else come out.
    Regarding your collection question -- if you declare the field as a
    java.util.Set, modifications of the collection will be much more efficient.
    -Patrick
    Claudius Gr__ver wrote:
    Hello again,
    there seems to be a problem with one-to-many relations involving
    inheritence...
    Let me describe the setting:
    class AbstractUsecase {
    // element-type=Account
    Set accounts;
    class Usecase extends AbstractUsecase {
    class Account extends AbstractAccount implements InstanceCallbacks {
    // element-type=AccountRevisionItem
    List revisions;
    AbstractUsecase uc;
    class AccountRevisionItem extends Account {
    long time;
    User user;
    As you can see a simple model (in uml it looks much more better).
    In the method jdoPreStore() of Account an object of type
    AccountRevisionItem will added to revisions. This new object holds the
    data of Account, the User and timestamp of the modifing. So we are able to
    trace every change on the date (user, date). Metadata looks like this:
    When i get a extent of all Accounts i can fetch all revisions of each
    Account.
    Now the problem: When i fetch all accounts of a usecase there are objects
    included of type Account AND AccountRevisionItem. The generated SQL code
    shows also why: ...t0.JDOCLASSX IN ('tolina.data.Account',
    'tolina.data.AccountRevisionItem')...
    Kodo tries when fetching a set of Accounts also all subclasses of
    Accounts! How can i say: this set contains only accounts and no fetching
    of subclasses is needed!
    I would be grateful for any help!
    PS: I noticed that kodo deletes all elements of a list when inserting a
    new element, i remember there a several faqs around this. Can you anyway
    give a work-a-round?
    Patrick Linskey [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • Key Method in one to many mapping

    I have problem in one to many mapping. I use a composite key and use get method of that key as Key Method, toplink seems not to realize this change, and can't acommodate that.
    any one had same problem?

    Could you explain in more detail what it is you are tyring to do? By 'Key Method' do you mean you are using a Map as the collection type of a OneToMany mapping? What do you mean by change? Are you changing the composit key?
    --Gordon                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • One to many problem onan existing shema

    I'm trying to do an insert in a database using one-to-many mapping.
    I have two tables on an existing schema.
    The two tables are:
    ANAG
    | ID_ANAG     | RAG_SOC |
    |-------------------------|
    |     1     | a name |
    |-------------------------|
    | ...     | .....     |
    |-------------------------|
    INDI
    | ID_INDI     | ID_ENTITA     | INDIRIZZO|
    |-------------------------------------------
    | 101          | 1          | address 1|
    |------------------------------------------|
    | 102          | 1          | address 2|
    |------------------------------------------|
    | 103          | ....          | ....     |
    |------------------------------------------|
    One ANAG can have m INDI. Given an ANAG I can find the related INDI(s)
    with the relation
    ANAG.ID_ANAG=INDI.ID_ENTITA
    My two java classes are:
    package domain;
    import java.util.*;
    public class Anagrafica
    private int idAnag; //ID_ANAG
    private String ragSoc;
    private HashSet indis;
    // default constructor
    //get and set methods
    package domain;
    public class Indi
    private int idIndi; //ID_INDI
    private long idAnag; //ID_ENTITA
    private String indirizzo; //INDIRIZZO
    private Anagrafica anagrafica;
    // default constructor
    //get and set methods
    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="indis">
    <collection element-type="domain.Indi"/>
    <extension vendor-name="kodo" key="inverse"
    value="anagrafica"/>
         </field>
    </class>
    </package>
    </jdo>
    Indi.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="Indi"
    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"/>
    <field name="idIndi" primary-key="true">
    <extension key="data-column" value="ID_INDI"
    vendor-name="kodo"/>
    </field>
    <field name="idAnag">
    <extension key="data-column" value="ID_ENTITA"
    vendor-name="kodo"/>
    </field>
    <field name="indirizzo">
    <extension key="data-column" value="INDIRIZZO"
    vendor-name="kodo"/>
    </field>
    <field name="anagrafica"/>
    </class>
    </package>
    </jdo>
    When I run the test program and I try to insert a new Anagrafica object I
    get the exception:
    [ C:3974641; S:1673361; T:3317565; D:09/10/02 16.03 ] INSERT INTO
    ANAG(ID_ANAG, RAG_SOC) VALUES
    (-914917554, 'A NEW RAGSOC')[ C:3974641; S:7389395; T:3317565; D:09/10/02
    16.03 ] INSERT INTO
    INDI(INDIRIZZO, IDANAG_ANAGRAFICAX, ID_INDI, ID_ENTITA) VALUES ('via 25
    dicembre', NULL,
    -914917554,0)javax.jdo.JDOFatalDataStoreException:
    com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper: [SQL=INSERT INTO
    INDI(INDIRIZZO,
    IDANAG_ANAGRAFICAX, ID_INDI, ID_ENTITA) VALUES ('via 25 dicembre', NULL,
    -914917554,0)] ORA-00904:
    invalid column name
    [code=904;state=42000]
    NestedThrowables:
    com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper: [SQL=INSERT INTO
    INDI(INDIRIZZO,
    IDANAG_ANAGRAFICAX, ID_INDI, ID_ENTITA) VALUES ('via 25 dicembre', NULL,
    -914917554, 0)] ORA-00904:
    invalid column name
    [ C:3974641; T:3317565; D:09/10/02 16.03 ] roll back data store
    transaction     at
    com.solarmetric.kodo.impl.jdbc.runtime.SQLExceptions.throwFatal(SQLExceptions.java:17)     at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.insert(JDBCStoreManager.java:421)     at
    com.solarmetric.kodo.runtime.StateManagerImpl.insert(StateManagerImpl.java:1783)     at
    com.solarmetric.kodo.runtime.PNewState.flush(PNewState.java:31)     at
    com.solarmetric.kodo.runtime.StateManagerImpl.flush(StateManagerImpl.java:372)     at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.flush(PersistenceManagerImpl.java:426)     at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.commit(PersistenceManagerImpl.java:295)     at
    test.AnagraficaJdo.main(AnagraficaJdo.java:49)NestedThrowablesStackTrace:java.sql.SQLException:
    ORA-00904: invalid column name
         at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:168)     at
    oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208)     at
    oracle.jdbc.ttc7.Oall7.receive(Oall7.java:543)     at
    oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1405)     at
    oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:822)     at
    oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:1446)     at
    oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1371)     at
    oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1900)     at
    oracle.jdbc.driver.OracleStatement.doScrollStmtExecuteQuery(OracleStatement.java:5290)     at
    oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:697)     at
    com.solarmetric.kodo.impl.jdbc.datasource.StatementImpl.executeUpdate(StatementImpl.java:78)     at
    com.solarmetric.kodo.impl.jdbc.sql.NonSelectingSQL.execute(NonSelectingSQL.java:40)     at
    com.solarmetric.kodo.impl.jdbc.ormapping.ClassMapping.insert(ClassMapping.java:391)     at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.insert(JDBCStoreManager.java:416)     at
    com.solarmetric.kodo.runtime.StateManagerImpl.insert(StateManagerImpl.java:1783)     at
    com.solarmetric.kodo.runtime.PNewState.flush(PNewState.java:31)     at
    com.solarmetric.kodo.runtime.StateManagerImpl.flush(StateManagerImpl.java:372)     at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.flush(PersistenceManagerImpl.java:426)     at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.commit(PersistenceManagerImpl.java:295)     at
    test.AnagraficaJdo.main(AnagraficaJdo.java:49)
    How can I resolve the problem of the presence of IDANAG_ANAGRAFICAX and
    have the 1-m relation?
    Thank you in advance.
    Mirko

    I've changed the Indi class and the metadata but I still get an exception:
    javax.jdo.JDOFatalDataStoreException:
    com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper:
    [SQL=INSERT INTO INDI
    (INDIRIZZO, IDANAG_ANAGRAFICAX, ID_INDI, IDANAGX) VALUES
    ('via 25 dicembre', NULL, -847766554, 0)]
    ORA-00904: invalid column name
    I know I'm missing something but I don't know what.
    I can't find any simple example of a one-to-many mapping of two tables on
    an existing schema.
    The final SQL should be: INSERT INTO INDI(INDIRIZZO, ID_ENTITA, ID_INDI)
    VALUES ('via 25 dicembre', -847766554, -847766554)
    thank you in advance for help
    Fred Lucas wrote:
    You should not have both primitive fields for the data in the tables and
    relations to other persistence-capable objects. So, your Indi class and
    metadata should probably look something like this:
    package domain;
    public class Indi
    private int idIndi; //ID_INDI
    private String indirizzo; //INDIRIZZO
    private Anagrafica anagrafica;
    // default constructor
    //get and set methods
    Indi.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="Indi"
    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"/>
    <field name="idIndi" primary-key="true">
    <extension key="data-column" value="ID_INDI"
    vendor-name="kodo"/>
    </field>
    <field name="indirizzo">
    <extension key="data-column" value="INDIRIZZO"
    vendor-name="kodo"/>
    </field>
    <field name="anagrafica">
    <extension key="data-column" value="ID_ENTITA"
    vendor-name="kodo"/>
    </field>
    </class>
    </package>
    </jdo>
    -Fred
    In article <[email protected]>, Mirko wrote:
    I'm trying to do an insert in a database using one-to-many mapping.
    I have two tables on an existing schema.
    The two tables are:
    ANAG
    | ID_ANAG     | RAG_SOC |
    |-------------------------|
    |     1     | a name |
    |-------------------------|
    | ...     | .....     |
    |-------------------------|
    INDI
    | ID_INDI     | ID_ENTITA     | INDIRIZZO|
    |-------------------------------------------
    | 101          | 1          | address 1|
    |------------------------------------------|
    | 102          | 1          | address 2|
    |------------------------------------------|
    | 103          | ....          | ....     |
    |------------------------------------------|
    One ANAG can have m INDI. Given an ANAG I can find the related INDI(s)
    with the relation
    ANAG.ID_ANAG=INDI.ID_ENTITA
    My two java classes are:
    package domain;
    import java.util.*;
    public class Anagrafica
    private int idAnag; //ID_ANAG
    private String ragSoc;
    private HashSet indis;
    // default constructor
    //get and set methods
    package domain;
    public class Indi
    private int idIndi; //ID_INDI
    private long idAnag; //ID_ENTITA
    private String indirizzo; //INDIRIZZO
    private Anagrafica anagrafica;
    // default constructor
    //get and set methods
    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="indis">
    <collection element-type="domain.Indi"/>
    <extension vendor-name="kodo" key="inverse"
    value="anagrafica"/>
         </field>
    </class>
    </package>
    </jdo>
    Indi.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="Indi"
    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"/>
    <field name="idIndi" primary-key="true">
    <extension key="data-column" value="ID_INDI"
    vendor-name="kodo"/>
    </field>
    <field name="idAnag">
    <extension key="data-column" value="ID_ENTITA"
    vendor-name="kodo"/>
    </field>
    <field name="indirizzo">
    <extension key="data-column" value="INDIRIZZO"
    vendor-name="kodo"/>
    </field>
    <field name="anagrafica"/>
    </class>
    </package>
    </jdo>
    When I run the test program and I try to insert a new Anagrafica object I
    get the exception:
    [ C:3974641; S:1673361; T:3317565; D:09/10/02 16.03 ] INSERT INTO
    ANAG(ID_ANAG, RAG_SOC) VALUES
    (-914917554, 'A NEW RAGSOC')[ C:3974641; S:7389395; T:3317565; D:09/10/02
    16.03 ] INSERT INTO
    INDI(INDIRIZZO, IDANAG_ANAGRAFICAX, ID_INDI, ID_ENTITA) VALUES ('via 25
    dicembre', NULL,
    -914917554,0)javax.jdo.JDOFatalDataStoreException:
    com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper: [SQL=INSERT INTO
    INDI(INDIRIZZO,
    IDANAG_ANAGRAFICAX, ID_INDI, ID_ENTITA) VALUES ('via 25 dicembre', NULL,
    -914917554,0)] ORA-00904:
    invalid column name
    [code=904;state=42000]
    NestedThrowables:
    com.solarmetric.kodo.impl.jdbc.sql.SQLExceptionWrapper: [SQL=INSERT INTO
    INDI(INDIRIZZO,
    IDANAG_ANAGRAFICAX, ID_INDI, ID_ENTITA) VALUES ('via 25 dicembre', NULL,
    -914917554, 0)] ORA-00904:
    invalid column name
    [ C:3974641; T:3317565; D:09/10/02 16.03 ] roll back data store
    transaction     at
    com.solarmetric.kodo.impl.jdbc.runtime.SQLExceptions.throwFatal(SQLExceptions.java:17)     at
    >>
    >>
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.insert(JDBCStoreManager.java:421)     at
    >>
    >>
    com.solarmetric.kodo.runtime.StateManagerImpl.insert(StateManagerImpl.java:1783)     at
    >>
    com.solarmetric.kodo.runtime.PNewState.flush(PNewState.java:31)     at
    com.solarmetric.kodo.runtime.StateManagerImpl.flush(StateManagerImpl.java:372)     at
    >>
    >>
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.flush(PersistenceManagerImpl.java:426)     at
    >>
    >>
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.commit(PersistenceManagerImpl.java:295)     at
    >>
    >>
    test.AnagraficaJdo.main(AnagraficaJdo.java:49)NestedThrowablesStackTrace:java.sql.SQLException:
    >>
    ORA-00904: invalid column name
         at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:168)     at
    oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208)     at
    oracle.jdbc.ttc7.Oall7.receive(Oall7.java:543)     at
    oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1405)     at
    oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:822)     at
    oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:1446)     at
    >>
    >>
    oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1371)     at
    >>
    >>
    oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1900)     at
    >>
    >>
    oracle.jdbc.driver.OracleStatement.doScrollStmtExecuteQuery(OracleStatement.java:5290)     at
    >>
    >>
    oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:697)     at
    >>
    >>
    com.solarmetric.kodo.impl.jdbc.datasource.StatementImpl.executeUpdate(StatementImpl.java:78)     at
    >>
    >>
    com.solarmetric.kodo.impl.jdbc.sql.NonSelectingSQL.execute(NonSelectingSQL.java:40)     at
    >>
    >>
    com.solarmetric.kodo.impl.jdbc.ormapping.ClassMapping.insert(ClassMapping.java:391)     at
    >>
    >>
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.insert(JDBCStoreManager.java:416)     at
    >>
    >>
    com.solarmetric.kodo.runtime.StateManagerImpl.insert(StateManagerImpl.java:1783)     at
    >>
    com.solarmetric.kodo.runtime.PNewState.flush(PNewState.java:31)     at
    com.solarmetric.kodo.runtime.StateManagerImpl.flush(StateManagerImpl.java:372)     at
    >>
    >>
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.flush(PersistenceManagerImpl.java:426)     at
    >>
    >>
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.commit(PersistenceManagerImpl.java:295)     at
    >>
    test.AnagraficaJdo.main(AnagraficaJdo.java:49)
    How can I resolve the problem of the presence of IDANAG_ANAGRAFICAX and
    have the 1-m relation?
    Thank you in advance.
    Mirko
    Fred Lucas
    SolarMetric Inc.
    202-595-2064 x1122
    http://www.solarmetric.com

  • Insert with one-to-many mapping

    Hi,
    I've got the following situation:
    - an object A with a vector of object B
    - I defined a one-to-many relation in the descriptor of A referencing a collection of B using indirection through valueHolderInterface, the "private owned" is also checked
    - I defined a one-to-one relation in the descriptor of B referencing the object A using indirection through valueHolderInterface
    - the bidirectional relationship is maintained.
    I try to insert a new object A with a new object B inside. The code is as follows:
    A = new A();
    B = new B();
    // ... set the A attribute values
    // ... set the B attribute values
    A.addB(B);
    UnitOfWork uow = session.acquireUnitOfWork();
    uow.registerNewObject(A);
    uow.commit();
    where addB(b) is as follows:
    ((java.util.Vector)bvector.getValue()).add(b);
    b.setA(this);
    Executing this code, the object A is inserted in the database but the object B is not. And I would like that the object B is also stored in the database. Do I really have to register it? I want to make the insert in just one transaction. Have anyone an idea? I tried a lot of different configurations and just one SQL insert order is generated by Toplink.
    Thanks,
    Frédéric

    Hi Don,
    This is with reference to your comments on the following oracel forum query "http://forums.oracle.com/forums/thread.jspa?messageID=508819&#55728;&#57235;" regarding 1:M mapping insertion problem.(Same one)
    Actually I also have the same kind of scenario but the data in not getting inserted to the detail table. It always gives ORA-1400 error as it is unable to populate the foreign key of parent in child table.
    Can you suggest if I am missing something.
    Your quick response will be appreciated.
    Message was edited by:
    user466708

  • How to insert data in a one-to-many relationship

    How do you insert data into the client, my model entity beans have a one-to-many relationship.
    PARENT ENTITY BEAN
    PARENT-ID
    PARENT-NAME
    The ejbCreate(Integer parentID,String name)
    CHILD ENTITY BEAN
    CHILD-ID
    CHILD-NAME
    PARENT-ID(foreign key of PARENTID).
    ejbCreate(Integer parentID,String name,String foreignparentID)
    In a jsp page i collect the parent details and 3 corresponding chld details in a text box.
    Can you please tell me how do i proceed from here...
    ie. how to i insert data into the entity beans..
    Do i pass the child as a collection, and within parents ejbCreate() method do i lookup for the childs home interface and insert one -by -one from the collection.
    1. Considering the above example, can some one pls tell how the ejbCreate() mehod signatures, for the parent and child entity beans should be.
    2. Pls also show some sample client code as to how to make an insertion.
    3. In case you are passing a collection of child data, then in what format does one have to insert into a collection and also how does the container know how to insert the values in the child table , bcoz we are passing as a collection.
    4.In case collections cannot be inserted do we need to iterate into the collection in parent's ejbCreate() method, and manually insert into the database of the childtable, thereby creating child entity beans.
    Thanks for your time and support...
    regards
    kartik

    Hi,
    3. In this case of course child's ejbCreate(and postCreate) looks like
    ejbCreate(Integer childID,String name,ParentLocal parent) {
    setId(Id);
    setName(name);
    ejbPostCreate(Integer childID,String name,ParentLocal parent) {
    setParent(parent);
    Here you don't need IDs, but it happens only using Locals, not Remotes, if I'm not wrong. Container does it itself.
    1. Of course, if you have parent.getChildren() and parent.setChildren() then you don't need any loops, but it should be done anyway in postCreate, because in ejbCreate there no parent exists yet.
    Once more 3: example - I'm using JBoss 3.2.5 as EJB container. It has tomcat inside and EJB and JSP+Struts use the same jvm. It means for me that I don't need to use remote interfaces, just locals. And in this case I can implement ejb-relations. So, a have the abstract method parent.getChildren() which returns Collection of ChildLocal - s and method parent.setChildren(Collection childrenLocals) which creates/modifies children by itself.
    I have not used remotes for a long time, but as I remember it was not possible to implement ejb-relations using remotes.
    regards,
    Gio

  • 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

  • Aggregate one-to-many relationship problem

    Hello,
    After migrating from Toplink 9i I've stumbled across a problem with our aggregate objects.
    Toplink Workbench reports no errors and generates a nice XML but in runtime I get this error whenever a aggregate function is used.
    [TopLink fin]: 2008.02.13 03:18:11.552--ServerSession(12626425)--Connection(29948747)--Thread(Thread[main,5,main])--SELECT DISTINCT t0.NPL_PACK_ID, t0.NPL_ID FROM NPL_MEDPROD t3, FASS_MEDPROD t2, NPL_MEDPROD t1, NPL_PACKAGE t0 WHERE (((t0.NPL_ID = t1._Presentation->NPL_ID_IN_REFERENCE_NPL_PACKAGE_NPL_MEDPROD_Test) AND ((t1.NPL_ID = t2.NPL_ID) AND (t3.NPL_ID LIKE '19750613000031%'))) AND (t3.NPL_ID = t2.NPL_ID))
    Caused by: Undantag [TOPLINK-4002] (Oracle TopLink - 10g Release 3 (10.1.3.1.0) (Build 061004)): oracle.toplink.exceptions.DatabaseException
    Internt undantag: java.sql.SQLException: ORA-00911: invalid character
    Felkod: 911
    I belive that problem resides in this clause :
    t1._Presentation->NPL_ID_IN_REFERENCE_NPL_PACKAGE_NPL_MEDPROD_Test
    I've created a small test project with just a couple of classes but the same aggregate problem occurs which has let me to believe the problem does not come from the migrating process which was my first guess. If anyone could help me discover what I am doing wrong it would be very appreciated. Below is my test project output.
    <?xml version="1.0" encoding="UTF-8"?>
    <toplink:object-persistence version="Oracle TopLink - 10g Release 3 (10.1.3.1.0) (Build 061004)" xmlns:opm="http://xmlns.oracle.com/ias/xsds/opm" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:toplink="http://xmlns.oracle.com/ias/xsds/toplink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <opm:name>test</opm:name>
    <opm:class-mapping-descriptors>
    <opm:class-mapping-descriptor xsi:type="toplink:relational-class-mapping-descriptor">
    <opm:class>se.lif.fass.fassdata.impl.FASSMedProdImpl</opm:class>
    <opm:alias>FASSMedProdImpl</opm:alias>
    <opm:primary-key>
    <opm:field table="FASS_MEDPROD" name="NPL_ID" xsi:type="opm:column"/>
    </opm:primary-key>
    <opm:events xsi:type="toplink:event-policy"/>
    <opm:querying xsi:type="toplink:query-policy"/>
    <opm:attribute-mappings>
    <opm:attribute-mapping xsi:type="toplink:one-to-one-mapping">
    <opm:attribute-name>_Medprod</opm:attribute-name>
    <opm:reference-class>schemas_npl.instance.impl.MedprodTypeImpl</opm:reference-class>
    <opm:private-owned>true</opm:private-owned>
    <opm:foreign-key>
    <opm:field-reference>
    <opm:source-field table="FASS_MEDPROD" name="NPL_ID" xsi:type="opm:column"/>
    <opm:target-field table="NPL_MEDPROD" name="NPL_ID" xsi:type="opm:column"/>
    </opm:field-reference>
    </opm:foreign-key>
    <opm:foreign-key-fields>
    <opm:field table="FASS_MEDPROD" name="NPL_ID" xsi:type="opm:column"/>
    </opm:foreign-key-fields>
    <toplink:batch-reading>true</toplink:batch-reading>
    <toplink:selection-query xsi:type="toplink:read-object-query"/>
    </opm:attribute-mapping>
    <opm:attribute-mapping xsi:type="toplink:direct-mapping">
    <opm:attribute-name>id</opm:attribute-name>
    <opm:read-only>true</opm:read-only>
    <opm:field table="FASS_MEDPROD" name="NPL_ID" xsi:type="opm:column"/>
    </opm:attribute-mapping>
    </opm:attribute-mappings>
    <toplink:descriptor-type>independent</toplink:descriptor-type>
    <toplink:instantiation/>
    <toplink:copying xsi:type="toplink:instantiation-copy-policy"/>
    <toplink:change-policy xsi:type="toplink:deferred-detection-change-policy"/>
    <toplink:tables>
    <toplink:table name="FASS_MEDPROD"/>
    </toplink:tables>
    </opm:class-mapping-descriptor>
    <opm:class-mapping-descriptor xsi:type="toplink:relational-class-mapping-descriptor">
    <opm:class>schemas_npl.instance.impl.MedprodTypeImpl</opm:class>
    <opm:alias>MedprodTypeImpl</opm:alias>
    <opm:primary-key>
    <opm:field table="NPL_MEDPROD" name="NPL_ID" xsi:type="opm:column"/>
    </opm:primary-key>
    <opm:events xsi:type="toplink:event-policy"/>
    <opm:querying xsi:type="toplink:query-policy"/>
    <opm:attribute-mappings>
    <opm:attribute-mapping xsi:type="toplink:aggregate-object-mapping">
    <opm:attribute-name>_Medprodpack</opm:attribute-name>
    <toplink:reference-class>schemas_npl.instance.impl.MedprodTypeImpl$MedprodpackTypeImpl</toplink:reference-class>
    <toplink:allow-null>false</toplink:allow-null>
    <toplink:field-translations>
    <toplink:field-translation>
    <toplink:source-field name="_Presentation->NPL_ID_IN_REFERENCE_NPL_PACKAGE_NPL_MEDPROD_Test" xsi:type="opm:column"/>
    <toplink:target-field table="NPL_MEDPROD" name="NPL_ID" xsi:type="opm:column"/>
    </toplink:field-translation>
    </toplink:field-translations>
    </opm:attribute-mapping>
    <opm:attribute-mapping xsi:type="toplink:direct-mapping">
    <opm:attribute-name>_Nplid</opm:attribute-name>
    <opm:field table="NPL_MEDPROD" name="NPL_ID" xsi:type="opm:column"/>
    </opm:attribute-mapping>
    <opm:attribute-mapping xsi:type="toplink:direct-mapping">
    <opm:attribute-name>id</opm:attribute-name>
    <opm:read-only>true</opm:read-only>
    <opm:field table="NPL_MEDPROD" name="NPL_ID" xsi:type="opm:column"/>
    </opm:attribute-mapping>
    </opm:attribute-mappings>
    <toplink:descriptor-type>independent</toplink:descriptor-type>
    <toplink:instantiation/>
    <toplink:copying xsi:type="toplink:instantiation-copy-policy"/>
    <toplink:change-policy xsi:type="toplink:deferred-detection-change-policy"/>
    <toplink:tables>
    <toplink:table name="NPL_MEDPROD"/>
    </toplink:tables>
    </opm:class-mapping-descriptor>
    <opm:class-mapping-descriptor xsi:type="toplink:relational-class-mapping-descriptor">
    <opm:class>schemas_npl.instance.impl.MedprodTypeImpl$MedprodpackTypeImpl</opm:class>
    <opm:alias>MedprodTypeImpl$MedprodpackTypeImpl</opm:alias>
    <opm:events xsi:type="toplink:event-policy"/>
    <opm:querying xsi:type="toplink:query-policy"/>
    <opm:attribute-mappings>
    <opm:attribute-mapping xsi:type="toplink:one-to-many-mapping">
    <opm:attribute-name>_Presentation</opm:attribute-name>
    <opm:reference-class>schemas_npl.instance.impl.MedprodTypeImpl$MedprodpackTypeImpl$PresentationTypeImpl</opm:reference-class>
    <opm:private-owned>true</opm:private-owned>
    <opm:target-foreign-key>
    <opm:field-reference>
    <opm:source-field table="NPL_PACKAGE" name="NPL_ID" xsi:type="opm:column"/>
    <opm:target-field name="_Presentation->NPL_ID_IN_REFERENCE_NPL_PACKAGE_NPL_MEDPROD_Test" xsi:type="opm:column"/>
    </opm:field-reference>
    </opm:target-foreign-key>
    <toplink:batch-reading>true</toplink:batch-reading>
    <toplink:container xsi:type="toplink:list-container-policy">
    <toplink:collection-type>com.sun.xml.bind.util.ListImpl</toplink:collection-type>
    </toplink:container>
    <toplink:selection-query xsi:type="toplink:read-all-query">
    <toplink:container xsi:type="toplink:list-container-policy">
    <toplink:collection-type>com.sun.xml.bind.util.ListImpl</toplink:collection-type>
    </toplink:container>
    </toplink:selection-query>
    </opm:attribute-mapping>
    </opm:attribute-mappings>
    <toplink:descriptor-type>aggregate</toplink:descriptor-type>
    <toplink:instantiation/>
    <toplink:copying xsi:type="toplink:instantiation-copy-policy"/>
    <toplink:change-policy xsi:type="toplink:deferred-detection-change-policy"/>
    </opm:class-mapping-descriptor>
    <opm:class-mapping-descriptor xsi:type="toplink:relational-class-mapping-descriptor">
    <opm:class>schemas_npl.instance.impl.MedprodTypeImpl$MedprodpackTypeImpl$PresentationTypeImpl</opm:class>
    <opm:alias>MedprodTypeImpl$MedprodpackTypeImpl$PresentationTypeImpl</opm:alias>
    <opm:primary-key>
    <opm:field table="NPL_PACKAGE" name="NPL_PACK_ID" xsi:type="opm:column"/>
    </opm:primary-key>
    <opm:events xsi:type="toplink:event-policy"/>
    <opm:querying xsi:type="toplink:query-policy"/>
    <opm:attribute-mappings>
    <opm:attribute-mapping xsi:type="toplink:direct-mapping">
    <opm:attribute-name>_Nplpackid</opm:attribute-name>
    <opm:field table="NPL_PACKAGE" name="NPL_PACK_ID" xsi:type="opm:column"/>
    </opm:attribute-mapping>
    <opm:attribute-mapping xsi:type="toplink:one-to-one-mapping">
    <opm:attribute-name>backref</opm:attribute-name>
    <opm:reference-class>schemas_npl.instance.impl.MedprodTypeImpl</opm:reference-class>
    <opm:foreign-key>
    <opm:field-reference>
    <opm:source-field table="NPL_PACKAGE" name="NPL_ID" xsi:type="opm:column"/>
    <opm:target-field table="NPL_MEDPROD" name="NPL_ID" xsi:type="opm:column"/>
    </opm:field-reference>
    </opm:foreign-key>
    <opm:foreign-key-fields>
    <opm:field table="NPL_PACKAGE" name="NPL_ID" xsi:type="opm:column"/>
    </opm:foreign-key-fields>
    <toplink:indirection xsi:type="toplink:value-holder-indirection-policy"/>
    <toplink:selection-query xsi:type="toplink:read-object-query"/>
    </opm:attribute-mapping>
    <opm:attribute-mapping xsi:type="toplink:direct-mapping">
    <opm:attribute-name>id</opm:attribute-name>
    <opm:read-only>true</opm:read-only>
    <opm:field table="NPL_PACKAGE" name="NPL_ID" xsi:type="opm:column"/>
    </opm:attribute-mapping>
    </opm:attribute-mappings>
    <toplink:descriptor-type>independent</toplink:descriptor-type>
    <toplink:instantiation/>
    <toplink:copying xsi:type="toplink:instantiation-copy-policy"/>
    <toplink:change-policy xsi:type="toplink:deferred-detection-change-policy"/>
    <toplink:tables>
    <toplink:table name="NPL_PACKAGE"/>
    </toplink:tables>
    </opm:class-mapping-descriptor>
    </opm:class-mapping-descriptors>
    <toplink:login xsi:type="toplink:database-login">
    <toplink:platform-class>oracle.toplink.platform.database.oracle.Oracle8Platform</toplink:platform-class>
    <toplink:user-name>fassadmin</toplink:user-name>
    <toplink:password>3CC3773C96563CA0C89634305615359CD62D1A19DF561D1E</toplink:password>
    <toplink:driver-class>oracle.jdbc.driver.OracleDriver</toplink:driver-class>
    <toplink:connection-url>jdbc:oracle:oci8:@DB2</toplink:connection-url>
    </toplink:login>
    </toplink:object-persistence>
    Regards
    /Jonas

    The issue is in the one-to-many mapping in the aggregate,
    <br>
    <opm:attribute-mapping xsi:type="toplink:one-to-many-mapping">
      <opm:attribute-name>_Presentation</opm:attribute-name>
      <opm:reference-class>schemas_npl.instance.impl.MedprodTypeImpl$MedprodpackTypeImpl$PresentationTypeImpl</opm:reference-class>
      <opm:private-owned>true</opm:private-owned>
      <opm:target-foreign-key>
        <opm:field-reference>
          <opm:source-field table="NPL_PACKAGE" name="NPL_ID" xsi:type="opm:column"/>
          <opm:target-field name="_Presentation->NPL_ID_IN_REFERENCE_NPL_PACKAGE_NPL_MEDPROD_Test" xsi:type="opm:column"/>
        </opm:field-reference>
      </opm:target-foreign-key>There is an issue with the Mapping Workbench and shared aggregates with one-to-many mappings and translating the foreign key fields. Did this work before, I would be surprized if it did, unless the 2.5 Builder was used?
    Anyway the easiest workaround is to either edit the XML and change the NPL_ID_IN_REFERENCE_NPL_PACKAGE_NPL_MEDPROD_Test column name to what it should be, or define a descriptor amendment method to define the one-to-many mapping with the correct field names.
    -- James : EclipseLink

  • One to many mapping problem

    In my JPA project I'm using these three classes:
    Cart.java:
    package com.spinnaker.pedja;
    import java.sql.Date;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashSet;
    import java.util.Set;
    import javax.persistence.*;
    @Entity(name = "Cart")
    @Table(schema = "shop")
    public class Cart {
         @Id
         @Column(name = "cart_id")
         private int Cart_id;
         @Column(name = "cart_date")
         private Date date;
          @OneToMany(mappedBy = "cartItemPK", targetEntity = CartItemPK.class)
          private Set cartitemCollection = new HashSet(0);
         @ManyToOne
         @JoinColumn(name = "customer_id")
         private Customer customer;
         public Customer getCustomer() {
              return customer;
         public void setCustomer(Customer customer) {
              this.customer = customer;
         public Cart() {
          public Set getCartitemCollection() {
          return cartitemCollection;
          public void setCartitemCollection(Set cartitemCollection) {
          this.cartitemCollection = cartitemCollection;
         public int getCart_id() {
              return Cart_id;
         public void setCart_id(int cart_id) {
              this.Cart_id = cart_id;
         public Date getDate() {
              return date;
         public void setDate(Date date) {
              this.date = date;
    }, CartItem.java:
    package com.spinnaker.pedja;
    import java.io.Serializable;
    import javax.persistence.*;
    @Entity
    @Table(schema = "shop")
    public class CartItem implements Serializable {
         @EmbeddedId
         @ManyToOne
    //     @JoinColumn(name = "cart_id")
         CartItemPK cartItemPK;
         @Column(name = "quantity")
         private int quantity;
         @Column(name = "unit_price")
         private double unit_price;
    //     @JoinColumn(name = "cart_id")
    //     private Cart cart;
    //      public Cart getCart() {
    //      return cart;
    //      public void setCart(Cart cart) {
    //      this.cart = cart;
         public CartItem() {
         public CartItemPK getCartItemPK() {
              return cartItemPK;
         public void setCartItemPK(CartItemPK cartItemPK) {
              this.cartItemPK = cartItemPK;
         public int getQuantity() {
              return quantity;
         public void setQuantity(int quantity) {
              this.quantity = quantity;
         public double getUnit_price() {
              return unit_price;
         public void setUnit_price(double unit_price) {
              this.unit_price = unit_price;
    }and CartItemPK.java:
    package com.spinnaker.pedja;
    import java.io.Serializable;
    import javax.persistence.*;
    @Table(schema="shop")
    @Embeddable
    public class CartItemPK implements Serializable{
         @Column(name="item_id",nullable=false)
         private int itemId;
    //     @ManyToOne
    //     @JoinColumn(name = "cart_id")
    //     private Cart cart;
         @Column(name="cart_id",nullable=false)
         private int cartId;
         public int getItemId() {
              return itemId;
         public void setItemId(int itemId) {
              this.itemId = itemId;
         public int getCartId() {
              return cartId;
         public void setCartId(int cartId) {
              this.cartId = cartId;
    I'm having problem with mapping one to many relationship between Cart and CartItem.I had to introduce CartItemPK class because CartItem has composite primary key.Help please!!!

    In my test class I'm using this code:
    Cart cart=em.find(Cart.class, 33);
              Set cartItems=cart.getCartitemCollection();
              for (Iterator iterator = cartItems.iterator(); iterator.hasNext();) {
                   CartItem cart_item = (CartItem) iterator.next();
                   System.out.println(cart_item.getCartItemPK().getCartId());
              }and this error happens:
    Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.spinnaker.pedja.Cart.cartitemCollection[com.spinnaker.pedja.CartItemPK]
         at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:247)
         at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:120)
         at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:159)
         at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:95)
         at com.spinnaker.pedja.test.Test.main(Test.java:30)
    Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.spinnaker.pedja.Cart.cartitemCollection[com.spinnaker.pedja.CartItemPK]
         at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:979)
         at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:530)
         at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:471)
         at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:43)
         at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1136)
         at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:296)
         at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1121)
         at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1211)
         at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:154)
         at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:847)
         at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:178)
         at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:235)
         ... 4 more
    I didn't find any example on the internet about my particular case.In the database,Cart and CartItem are conected via cart_id field.But in my JPA project,cart_id field is a part of a composite key CarItemPK.

  • One-to-many relationship: problem with several tables on the one side...

    Hello
    I'm having problems developing a database for a content management system. Apart from details, I've got one main table, that holds the tree structure of the content ("resources") and several other tables that contain data of a particular datatype ("documents", "images", etc.). Now, there's one-to-many relationship between "resources" table and all the datatype tables - that is, in the "resources" table there's "resource_id" column, being a foreign key referenced to the "id" columns in the datatype tables.
    The problem is that this design is deficient. I can't tell form the "resource_id" column from which datatype table to get the data. It seems to me that one-to-many relationship only works with two tables. If the data on the one side of the relationship is contained in several tables, problems arise.
    Anybody knows a solution? I would be obliged.
    Regards
    Havocado

    Hi;
    A simple way may be create a view on referenced tables:
    Connected to Oracle Database 10g Express Edition Release 10.2.0.1.0
    Connected as hr
    SQL>
    SQL> drop table resources;
    Table dropped
    SQL> create table resources(id number, name varchar2(12));
    Table created
    SQL> insert into resources values(1,'Doc....');
    1 row inserted
    SQL> insert into resources values(2,'Img....');
    1 row inserted
    SQL> drop table documents;
    Table dropped
    SQL> create table documents(id number, resource_id number,type varchar2(12));
    Table created
    SQL> insert into documents values(1,1,'txt');
    1 row inserted
    SQL> drop table images;
    Table dropped
    SQL> create table images(id number, resource_id number,path varchar2(24));
    Table created
    SQL> insert into images values(1,2,'/data01/images/img01.jpg');
    1 row inserted
    SQL> create or replace view vw_resource_ref as
      2    select id, resource_id, type, null as path from documents
      3      union
      4     select id, resource_id, null as type, path from images;
    View created
    SQL> select * from resources r inner join vw_resource_ref rv on r.id = rv.resource_id;
            ID NAME                 ID RESOURCE_ID TYPE         PATH
             1 Doc....               1           1 txt         
             2 Img....               1           2              /data01/images/img01.jpg
    SQL> Regards....

  • One to many table insert in JDBC

    hi all, I have an online form when it submit the value will get into three table, one child table is one to many relation to parent , like
    parent  table have(     UserId        int Not null,     UniversityN      varchar(10) Not null,   ...   PRIMARY KEY  (UserId)   PaymentId          int Not null  auto_increment ,     UserId        int Not null, ) child Table( PaymentId          int Not null  auto_increment , UserId        int Not null, UniversityN      varchar(10) Not null, record1            varchar(50) Not null, record2            varchar(50) Not null, record13          varchar(50) Not null,     PRIMARY KEY  (PaymentId),     FOREIGN Key(UserId) REFERENCES Parent(UserId) on Delete     Cascade on update cascade)Type=InnoDB DEFAULT CHARSET=utf8; )
    then I have
    conn.setAutoCommit(false); calstat1 = (CallableStatement) conn.prepareCall(                     "{ call Insert_Parent(?,?,?,?,?,?,?,?,?,?,?,? )}"); calstat2 = (CallableStatement) conn.prepareCall(                     "{ call Insert_ChildRecords(?,?,?,?,?,?,?,?,?,?,?,? )}");
    and the UniversityN , recored1, record2, record3 all come from the input form, how can i handle this one to many insert? for each submit the parent table always one row, and the child table is a lease one up to five rows the if the did have five the userId , and UniversityN is same, but the recore 1. record2... is different
    thank you

    I think you have a problem with your database table definitions that you need to fix before coding java.
    In the above, I dont think you need the first PaymentId (in the 'have' table). I also dont think your tables are normalized since I see 'UniversityN' in both the parent and child record. Also, you should rename your tables to something meaningfull rather than 'have' and 'table'. Also, rename the fields better. Ideally get your friendly neighborhood DBA to review your tables. Only when they are well defined should you start to work on java.
    Here's an example:
    parent  table:
    Customer(
        id                number, not null, primary key, must be unique, auto increment
        userId         number, not null, natural key, must be unique
        universityN  varchar(10), Not null
    child Table:
    Payment(
        id                      number, not null, primary key, must be unique, auto increment
       customer_id        number, not null, foreign key to the customer table's id field
       record1               varchar(50), not null,
       record2               varchar(50), not null,
       record3               varchar(50), not null,
        Cascade on delete record when parent is deleted
        dont cascase update record
    )Note: in the above, record1,record2, record3 should probably be put in its own table, with a foreign key back to the payment table.
    Note: each table in your database has its own id that is auto generated. Some have a natural key (like userID) that can be used to look up records independent of the auto generated key.
    Note the customer_id (foreign key) has the name of table it refers to (customer) and the key its refering to in that table (id).
    Note: when you insert a new customer, you need to get the newly generated id. Use the natural key to retreive the id in order to put it in the new payment table's customer_id field.
    I suggest you dont cascade delete any child table. Do it programmatically so you can better learn the issues that come up as you insert, update, and delete various parent and child combinations.

Maybe you are looking for