JPA OneToMany mapping whit toplink...

I have a problem when i want to map a OneToMany unidirectional relation using toplink. Toplink maps the relation as a ManyToMany relation instead?
Code in a class called Car:
@OneToMany(cascade={CascadeType.PERSIST, CascadeType.REMOVE})
public List<Wheel> getWheels() { return wheels; }
public void setWheels(List<Wheel> wheels) { this.wheels = wheels; }
toplink output:
[TopLink Config]: 2006.11.07 11:41:41.984--ServerSession(9505840)--The target entity (reference) class for the one to many mapping element [public java.util.List entities.Car.getWheels()] is being defaulted to: class entities.Wheel.
[TopLink Config]: 2006.11.07 11:41:41.984--ServerSession(9505840)--The join table name for the many to many mapping [public java.util.List entities.Car.getWheels()] is being defaulted to: CAR_WHEEL.
[TopLink Config]: 2006.11.07 11:41:41.984--ServerSession(9505840)--The source primary key column name for the many to many mapping [public java.util.List entities.Car.getWheels()] is being defaulted to: CARID.
[TopLink Config]: 2006.11.07 11:41:41.984--ServerSession(9505840)--The source foreign key column name for the many to many mapping [public java.util.List entities.Car.getWheels()] is being defaulted to: Car_CARID.
[TopLink Config]: 2006.11.07 11:41:41.984--ServerSession(9505840)--The target primary key column name for the many to many mapping [public java.util.List entities.Car.getWheels()] is being defaulted to: WHEELID.
[TopLink Config]: 2006.11.07 11:41:41.984--ServerSession(9505840)--The target foreign key column name for the many to many mapping [public java.util.List entities.Car.getWheels()] is being defaulted to: wheels_WHEELID.
When i use @JoinColumn i get a message from toplink that says that it is not required when the relation is unidirectional so it is not possible to identify the foreign key..

The JPA Spec does not allow unidirectional 1-m relationships without using a join table, they must always be bidirectional. You must define a 1-1 back-reference and use the "mapped-by" in the 1-m mapping referencing the 1-1.

Similar Messages

  • Problem of cycle and stackoverflow when using JPA @OneToMany mapping Tag

    Hello everyone!
    Description:
    We are using the tag @OneToMany to map a collection of objects in an entity. In the other side, we use the tag @ManyToOne to map the father.
    Our simple example for testing consist of the following entities:
    This is the class Child:
    @Entity
    @Table(name="TEST_CHILD")
    public class Child implements Serializable{
    @Id
    @Column(name="ID_CHILD")
    private Long id;
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="ID_FATHER", referencedColumnName="ID_FATHER")
    private Father father;
    and this is the Father class:
    @Entity
    @Table(name="TEST_FATHER")
    public class Father implements Serializable{
    @Id
    @Column(name="ID_FATHER")
    private Long id;
    @OneToMany(mappedBy="father", fetch=FetchType.EAGER)
    private List<Child> children;
    Problem:
    When a select over this entities is realized, we are getting the folling exception:
    The following Error is thrown by the VM [java.lang.StackOverflowError]. ErrorQueueHandler will just trace it. The caller component should take care to process it properly.
    java.lang.StackOverflowError
    at java.lang.Class.searchMethods(Class.java:2646)
    We've already used @OneToMany and @ManyToOne mapping in many other projects, and we've tried different parameters on the tags as well, but we still getting the exception. If applying fetch mode Lazy to the @OneToMany we had an detatched exception, cause ou the context. Anyways, we need and would like to use the EAGER loading mode.
    So what seems to happen is that the application runs into a cycle when loading the "father" attribute of Child, recreating the list collection within it.
    This same configuration works just fine in other implementations (i.e.: Hibernate JPA implementation), and many other examples over the web are not different of our implementation.
    Any suggestion of how we could solve this problem? Is this a standart behavior of mapping using Sap JPA?
    Evandro Pomatti
    Edited by: Evandro Pomatti on Dec 9, 2010 9:55 PM

    hi evandro,
    now I got same kind of error, how did you fix, pls help if you have remembered,
    hi all,
    I am getting folowing error in my JAVA portal system when executing webservices in WSnavigator.
    if anyone would have been faced this kind of error pls help me.
    The following Error is thrown by the VM [java.lang.StackOverflowError]. ErrorQueueHandler will just trace it. The caller component should take care to process i
    t properly.
    completere error log
    #2.#2014 04 27 23:52:42:197#0-500#Warning#com.sap.engine.core.thread.impl3.ErrorQueueHandler#
    com.sap.ASJ.krn_thd.000025#BC-JAS-COR#kernel.sda#C0000AF060EF002D000001A901AA0076###com.sap.engine.core.thread.impl3.ErrorQueueHandler#Guest#0##9586B2DBCCBD11E3
    A75E0000033325C2#9586b2dbccbd11e3a75e0000033325c2#9586b2dbccbd11e3a75e0000033325c2#0#Thread[ErrorQueueWatchDog,5,main]#Plain##
    The following Error is thrown by the VM [java.lang.StackOverflowError]. ErrorQueueHandler will just trace it. The caller component should take care to process i
    t properly.
    java.lang.StackOverflowError
            at java.security.AccessController.doPrivileged(Native Method)
            at java.io.FilePermission.init(FilePermission.java:183)
            at java.io.FilePermission.<init>(FilePermission.java:249)
            at sun.net.www.protocol.file.FileURLConnection.getPermission(FileURLConnection.java:198)
            at sun.security.provider.PolicyFile.canonicalizeCodebase(PolicyFile.java:1784)
            at sun.security.provider.PolicyFile.access$700(PolicyFile.java:264)
            at sun.security.provider.PolicyFile$7.run(PolicyFile.java:1247)
            at java.security.AccessController.doPrivileged(Native Method)
            at sun.security.provider.PolicyFile.getPermissions(PolicyFile.java:1243)
            at sun.security.provider.PolicyFile.getPermissions(PolicyFile.java:1190)
            at com.sap.engine.services.security.jacc.provider.PolicyImpl.implies(PolicyImpl.java:71)
            at com.sap.security.core.UmePolicy.implies(UmePolicy.java:696)
            at com.sap.security.core.role.jacc.JACCPolicy.implies(JACCPolicy.java:367)
            at java.security.ProtectionDomain.implies(ProtectionDomain.java:222)
            at java.security.AccessControlContext.checkPermission(AccessControlContext.java:354)
            at java.security.AccessController.checkPermission(AccessController.java:549)
            at com.sap.engine.services.keystore.impl.security.CodeBasedSecurityConnector.checkPermissions_readEntry(CodeBasedSecurityConnector.java:542)
    and also find heap log info
    -----------  H E A P   C H E C K  -----------
    Suspension of other threads succeeded.
    6 Java thread local allocation buffers currently in use.
    Scanning young generation space 314368K,   1% used [0x0a00020000000000, 0x0a00020000334838, 0x0a00020013300000)
    Scanning young generation space 157184K,   0% used [0x0a00020013300000, 0x0a00020013300000, 0x0a0002001cc80000)
    Scanning young generation space 157184K,   0% used [0x0a0002001cc80000, 0x0a0002001cc80000, 0x0a00020026600000)
    Scanning old generation space 2516992K,  21% used [0x0a00020026600000, 0x0a000200c0000000)
    Scanning permanent generation space 409600K,  99% used [0x0a000200c0000000, 0x0a000200d9000000)
    Checked the complete java heap.
    ---  N O   H E A P   C O R R U P T I O N  ---
    -----------  R E G I S T E R   R E G I O N S  -----------
    Register pc points to 0x09000000332ef3a8, which is not a known memory location
    Register lr points to 0x09000000332ef388, which is not a known memory location
    Register ctr points to 0x0900000033421bc0, which is not a known memory location
    Register r0 points to 0x0000000000000000, which is not a known memory location
    Register r1 points into the stack of JavaThread "HTTP Worker [@1753615133]" [_thread_in_vm (_call_back), id=25193, stack(0x000000011a5ef888,0x000000011a6ef888)]
    Dump of memory region around register r1 at 0x000000011a6e2a70
       0x000000011a6e29f0 00 00 00 01 1A 6E 2A 70 00 00 00 00 00 00 00 15 [.....n*p........]
       0x000000011a6e2a00 09 00 00 00 33 63 12 DC 09 00 10 00 A6 6A F9 60 [....3c.......j.`]
       0x000000011a6e2a10 00 00 00 00 12 4C 35 C0 0A 00 01 00 16 3D 60 78 [.....L5......=`x]
       0x000000011a6e2a20 09 00 00 00 33 FB 54 98 00 00 00 00 33 F4 90 28 [....3.T.....3..(]
       0x000000011a6e2a30 09 00 10 00 A6 4D 98 10 00 00 00 01 1A 6E 2A E8 [.....M.......n*.]
       0x000000011a6e2a40 00 00 00 00 00 00 00 00 00 00 00 00 15 A8 00 69 [...............i]
       0x000000011a6e2a50 00 00 00 00 15 A8 00 69 09 00 00 00 33 F4 90 38 [.......i....3..8]
       0x000000011a6e2a60 00 00 00 00 00 00 01 08 00 00 00 00 00 00 00 00 [................]
    => 0x000000011a6e2a70 00 00 00 01 1A 6E 2B 60 00 00 00 00 00 00 00 08 [.....n+`........]
    Register r2 points to 0x09001000a66af960, which is not a known memory location
    Register r3 points to 0x00000001188fa130, which is not a known memory location
    Register r4 points to 0x0a000100163d6098, which is not a known memory location
    Register r5 points to 0x0900000033f49038, which is not a known memory location
    Register r6 points to 0x0000000000000108, which is not a known memory location
    Register r7 points to 0x09001000a648c308, which is not a known memory location
    Register r8 points to 0x09001000a64cf2b4, which is not a known memory location
    Register r9 points to 0x0000000000000000, which is not a known memory location
    Register r10 points to 0x0000000000000000, which is not a known memory location
    Register r11 points to 0x0000000000000000, which is not a known memory location
    Register r12 points to 0x09000000332ef388, which is not a known memory location
    Register r13 points into the stack of JavaThread "HTTP Worker [@2116488621]" [_thread_in_native (_at_safepoint), id=25450, stack(0x000000011a6f4888,0x000000011a
    7f4888)]
    [error occurred during error reporting (dumping memory regions for register values), id 0xb
    Exception details: SIGSEGV at pc=0
    Problematic frame: v  ~StubRoutines::SafeFetch32 (sp=0x000000011a6e1240) (pc=0x0a00010000067b58)]
    hs_err_pid26214604.log: END

  • JPA @OneToMany Question

    Hello, there.
    How can I set OneToMany relationship in JPA, when child's identity(uniqueness) needs parent's primary key?
    Every books that I have only talk about the @PrimaryKeyJoinColumn with OneToOne mapping.
    Every books that I have only talk about the @OneToMany mapping with non-identifying relationships.
    Every google pages has no exception.
    @Entity public class Parent implements Serializable {
        @Id public int id;
        @OneToMany public Collection<Child> child;
    @Entity public class Child implements Serializable {
        @Id public int child_id;
        @ManyToOne Parent parent; // NOT FK, BUT PK ?????????????
    }

    This is something that JPA 1.0 does not handle too well. Hopefully JPA 2.0 will be easier.
    Basically you need to duplicate the id field and use a @PrimaryKeyJoinColumn. But some JPA providers have alternatives.
    See,
    [http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_Relationships]
    The OneToOne would be a ManyToOne for your example, but mainly the same.
    -- James : [http://www.eclipselink.org]

  • Problem with onetomany mapping

    I have the problem with onetomany mapping:
    Customer(CMP)1-->n CustomerAddress 1-->1 Customer
    The problem is first time i create a Customer and add the addresses, it'ok; but I always got this exception second time:
    EXCEPTION DESCRIPTION: The object [[email protected]], of class [class g
    ov.nasa.echo.business.ejb.customerprofile.CustomerAddress], with identity hashcode (System.identityHashCode()) [1,073,18
    5],
    is not from this UnitOfWork object space, but the parent session's. The object was never registered in this UnitOfWork,
    but read from the parent session and related to an object registered in the UnitOfWork. Ensure that you are correctly
    registering your objects. If you are still having problems, you can use the UnitOfWork.validateObjectSpace() method to
    help debug where the error occurred. For more information, see the manual or FAQ.

    It depends on the usecase of your situation, but it sounds like you may need to make use of the merge capabilities of TopLink. Check out the docs starting on page 6-4 of the "CMP For users of BEA WebLogic Server Guide"
    - Don

  • Exceptions while Opening a older toplink map in toplink 11g workbench

    Hi
    I have a toplink map used with toplink 10g. Now that after moving to toplink 11g I am unable to open the map using workbench. I am getting the following exception while opening.
    Inputs to solve this probelm are welcomed.
    oracle.toplink.workbench.framework.OpenException: Exception [TOPLINK-106] (Oracle TopLink - 11g (11.1.1.0.1) (Build 081030)): oracle.toplink.exceptions.DescriptorException
    Exception Description: The method [legacySetDatabasePlatformNameForTopLink] on the object is throwing an exception.
    Argument: [null]
    Internal Exception: java.lang.reflect.InvocationTargetException
    Target Invocation Exception: java.lang.IllegalArgumentException: missing database platform named: null
    Mapping: oracle.toplink.mappings.DirectToFieldMapping[databasePlatformName-->platform-name]
    Descriptor: XMLDescriptor(oracle.toplink.workbench.mappingsmodel.db.MWDatabase --> [DatabaseTable(database)])
         at oracle.toplink.workbench.mappingsplugin.MappingsPlugin.open(MappingsPlugin.java:293)
         at oracle.toplink.workbench.framework.internal.FrameworkApplication.open(FrameworkApplication.java:689)
         at oracle.toplink.workbench.framework.internal.FrameworkNodeManager.openCallback(FrameworkNodeManager.java:341)
         at oracle.toplink.workbench.framework.internal.RunnableProjectLoader.run2(RunnableProjectLoader.java:76)
         at oracle.toplink.workbench.framework.internal.RunnableProjectLoader.run(RunnableProjectLoader.java:63)
         at java.lang.Thread.run(Thread.java:595)
    Caused by: Exception [TOPLINK-106] (Oracle TopLink - 11g (11.1.1.0.1) (Build 081030)): oracle.toplink.exceptions.DescriptorException
    Exception Description: The method [legacySetDatabasePlatformNameForTopLink] on the object is throwing an exception.
    Argument: [null]
    Internal Exception: java.lang.reflect.InvocationTargetException
    Target Invocation Exception: java.lang.IllegalArgumentException: missing database platform named: null
    Mapping: oracle.toplink.mappings.DirectToFieldMapping[databasePlatformName-->platform-name]
    Descriptor: XMLDescriptor(oracle.toplink.workbench.mappingsmodel.db.MWDatabase --> [DatabaseTable(database)])
         at oracle.toplink.exceptions.DescriptorException.targetInvocationWhileSettingValueThruMethodAccessor(DescriptorException.java:1702)
         at oracle.toplink.internal.descriptors.MethodAttributeAccessor.setAttributeValueInObject(MethodAttributeAccessor.java:202)
         at oracle.toplink.mappings.DatabaseMapping.setAttributeValueInObject(DatabaseMapping.java:1228)
         at oracle.toplink.mappings.DatabaseMapping.readFromRowIntoObject(DatabaseMapping.java:1118)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:277)
         at oracle.toplink.sdk.SDKAggregateObjectMapping.buildCompositeObject(SDKAggregateObjectMapping.java:58)
         at oracle.toplink.mappings.foundation.AbstractCompositeObjectMapping.valueFromRow(AbstractCompositeObjectMapping.java:231)
         at oracle.toplink.mappings.DatabaseMapping.readFromRowIntoObject(DatabaseMapping.java:1117)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:277)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:582)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:439)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:389)
         at oracle.toplink.queryframework.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:511)
         at oracle.toplink.queryframework.ReadObjectQuery.executeObjectLevelReadQuery(ReadObjectQuery.java:433)
         at oracle.toplink.queryframework.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:874)
         at oracle.toplink.queryframework.DatabaseQuery.execute(DatabaseQuery.java:674)
         at oracle.toplink.queryframework.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:835)
         at oracle.toplink.queryframework.ReadObjectQuery.execute(ReadObjectQuery.java:397)
         at oracle.toplink.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:2260)
         at oracle.toplink.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1074)
         at oracle.toplink.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1058)
         at oracle.toplink.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1017)
         at oracle.toplink.internal.sessions.AbstractSession.readObject(AbstractSession.java:2822)
         at oracle.toplink.workbench.mappingsio.legacy.PersistenceTools50.readMWProjectNamed(PersistenceTools50.java:323)
         at oracle.toplink.workbench.mappingsio.legacy.LegacyIOFacade.read50Project(LegacyIOFacade.java:21)
         at oracle.toplink.workbench.mappingsio.ProjectReader.readLegacyProject(ProjectReader.java:248)
         at oracle.toplink.workbench.mappingsio.ProjectReader.read(ProjectReader.java:104)
         at oracle.toplink.workbench.mappingsio.ProjectIOManager.read(ProjectIOManager.java:59)
         at oracle.toplink.workbench.mappingsplugin.MappingsPlugin.open(MappingsPlugin.java:289)
         ... 5 more
    Caused by: java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at oracle.toplink.internal.descriptors.MethodAttributeAccessor.setAttributeValueInObject(MethodAttributeAccessor.java:174)
         at oracle.toplink.mappings.DatabaseMapping.setAttributeValueInObject(DatabaseMapping.java:1228)
         at oracle.toplink.mappings.DatabaseMapping.readFromRowIntoObject(DatabaseMapping.java:1118)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:277)
         at oracle.toplink.sdk.SDKAggregateObjectMapping.buildCompositeObject(SDKAggregateObjectMapping.java:58)
         at oracle.toplink.mappings.foundation.AbstractCompositeObjectMapping.valueFromRow(AbstractCompositeObjectMapping.java:231)
         at oracle.toplink.mappings.DatabaseMapping.readFromRowIntoObject(DatabaseMapping.java:1117)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:277)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:582)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:439)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:389)
         at oracle.toplink.queryframework.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:511)
         at oracle.toplink.queryframework.ReadObjectQuery.executeObjectLevelReadQuery(ReadObjectQuery.java:433)
         at oracle.toplink.queryframework.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:874)
         at oracle.toplink.queryframework.DatabaseQuery.execute(DatabaseQuery.java:674)
         at oracle.toplink.queryframework.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:835)
         at oracle.toplink.queryframework.ReadObjectQuery.execute(ReadObjectQuery.java:397)
         at oracle.toplink.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:2260)
         at oracle.toplink.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1074)
         at oracle.toplink.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1058)
         at oracle.toplink.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1017)
         at oracle.toplink.internal.sessions.AbstractSession.readObject(AbstractSession.java:2822)
         at oracle.toplink.workbench.mappingsio.legacy.PersistenceTools50.readMWProjectNamed(PersistenceTools50.java:323)
         at oracle.toplink.workbench.mappingsio.legacy.LegacyIOFacade.read50Project(LegacyIOFacade.java:21)
         at oracle.toplink.workbench.mappingsio.ProjectReader.readLegacyProject(ProjectReader.java:248)
         at oracle.toplink.workbench.mappingsio.ProjectReader.read(ProjectReader.java:104)
         at oracle.toplink.workbench.mappingsio.ProjectIOManager.read(ProjectIOManager.java:59)
    Caused by: java.lang.IllegalArgumentException: missing database platform named: null
         at oracle.toplink.workbench.platformsmodel.DatabasePlatformRepository.platformNamed(DatabasePlatformRepository.java:334)
         at oracle.toplink.workbench.mappingsmodel.db.MWDatabase.setDatabasePlatformNameForTopLink(MWDatabase.java:1013)
         at oracle.toplink.workbench.mappingsmodel.db.MWDatabase.legacySetDatabasePlatformNameForTopLink(MWDatabase.java:1133)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at oracle.toplink.internal.descriptors.MethodAttributeAccessor.setAttributeValueInObject(MethodAttributeAccessor.java:174)
         at oracle.toplink.mappings.DatabaseMapping.setAttributeValueInObject(DatabaseMapping.java:1228)
         at oracle.toplink.mappings.DatabaseMapping.readFromRowIntoObject(DatabaseMapping.java:1118)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:277)
         at oracle.toplink.sdk.SDKAggregateObjectMapping.buildCompositeObject(SDKAggregateObjectMapping.java:58)
         at oracle.toplink.mappings.foundation.AbstractCompositeObjectMapping.valueFromRow(AbstractCompositeObjectMapping.java:231)
         at oracle.toplink.mappings.DatabaseMapping.readFromRowIntoObject(DatabaseMapping.java:1117)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:277)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:582)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:439)
         at oracle.toplink.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:389)
         at oracle.toplink.queryframework.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:511)
         at oracle.toplink.queryframework.ReadObjectQuery.executeObjectLevelReadQuery(ReadObjectQuery.java:433)
         at oracle.toplink.queryframework.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:874)
         at oracle.toplink.queryframework.DatabaseQuery.execute(DatabaseQuery.java:674)
         at oracle.toplink.queryframework.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:835)
         at oracle.toplink.queryframework.ReadObjectQuery.execute(ReadObjectQuery.java:397)
         at oracle.toplink.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:2260)
         at oracle.toplink.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1074)
         at oracle.toplink.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1058)
         at oracle.toplink.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1017)
         at oracle.toplink.internal.sessions.AbstractSession.readObject(AbstractSession.java:2822)
         at oracle.toplink.workbench.mappingsio.legacy.PersistenceTools50.readMWProjectNamed(PersistenceTools50.java:323)
         at oracle.toplink.workbench.mappingsio.legacy.LegacyIOFacade.read50Project(LegacyIOFacade.java:21)
         at oracle.toplink.workbench.mappingsio.ProjectReader.readLegacyProject(ProjectReader.java:248)
         at oracle.toplink.workbench.mappingsio.ProjectReader.read(ProjectReader.java:104)
         at oracle.toplink.workbench.mappingsio.ProjectIOManager.read(ProjectIOManager.java:59)
         at oracle.toplink.workbench.mappingsplugin.MappingsPlugin.open(MappingsPlugin.java:289)
         at oracle.toplink.workbench.framework.internal.FrameworkApplication.open(FrameworkApplication.java:689)
         at oracle.toplink.workbench.framework.internal.FrameworkNodeManager.openCallback(FrameworkNodeManager.java:341)
         at oracle.toplink.workbench.framework.internal.RunnableProjectLoader.run2(RunnableProjectLoader.java:76)
         at oracle.toplink.workbench.framework.internal.RunnableProjectLoader.run(RunnableProjectLoader.java:63)
         at java.lang.Thread.run(Thread.java:595)
    Sree

    Hi Sree,
    If you could email me a copy of the whole mapping workbench project, I can probably fix this issue for you.
    Thanks,
    Les

  • JPA  -  tree structure mapping    with toplink essential

    I'll try to explain it correctly.
    I store a tree structure in a database. I have just two tables:
    Node which contain a id , and some other info.
    Tree which contain a parent and child
    parent and child are ids from node.
    Since each node can have several childs, and each node can have several parents, I had try a @ManyToMany relationship without sucess.
    Here one small example of my tries :
    @Entity
    @Table(name="node")
    public class Node {
    @Id private int id;
    private List<Node> childs;
    private List<Node> parents;
    @ManyToMany
    @JoinTable(name="Tree")
    public List<Node> getParents(){
         return parents;
    @ManyToMany(mappedBy="parents")
    public List<Node> getChilds(){
         return childs;
    }But I always got several error.
    Anyone have a working example that look like mine ?
    Even after googling for several hours I still find nothing.
    If it helps, I use toplink essential for my persistance layer.

    Please see http://www.oracle.com/technetwork/middleware/toplink/index-085257.html for information on TopLink JPA support.
    So as of TopLink 11, you will need to use EclipseLink's org.eclipse.persistence.jpa.PersistenceProvider as the provider class for JPA support, which is in the eclipselink.jar.
    Best Regards,
    Chris

  • OneToMany Mapping Exception - can anybody help

    SEVERE: >>java.lang.ExceptionInInitializerError: null
    javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0 (Build b40-rc (03/21/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupExceptionException Description: predeploy for PersistenceUnit [dmsPU] failed.
    Internal Exception: Exception [TOPLINK-7154] (Oracle TopLink Essentials - 2.0 (Build b40-rc (03/21/2007))): oracle.toplink.essentials.exceptions.ValidationException
    Exception Description: The attribute [mPackagepartses] in entity class [class com.adityas.jpa.masters.part.MPart] has a mappedBy value of [part] which does not exist in its owning entity class [class com.adityas.jpa.masters.packageParts.MPackageparts]. If the owning entity class is a @MappedSuperclass, this is invalid, and your attribute should reference the correct subclass.
    oracle.toplink.essentials.exceptions.EntityManagerSetupException: Exception Description: predeploy for PersistenceUnit [dmsPU] failed.
    Internal Exception: Exception [TOPLINK-7154] (Oracle TopLink Essentials - 2.0 (Build b40-rc (03/21/2007))): oracle.toplink.essentials.exceptions.ValidationException
    Exception Description: The attribute [mPackagepartses] in entity class [class com.adityas.jpa.masters.part.MPart] has a mappedBy value of [part] which does not exist in its owning entity class [class com.adityas.jpa.masters.packageParts.MPackageparts]. If the owning entity class is a @MappedSuperclass, this is invalid, and your attribute should reference the correct subclass.
    Local Exception Stack:
    Exception [TOPLINK-7154] (Oracle TopLink Essentials - 2.0 (Build b40-rc (03/21/2007))): oracle.toplink.essentials.exceptions.ValidationException
    Exception Description: The attribute [mPackagepartses] in entity class [class com.adityas.jpa.masters.part.MPart] has a mappedBy value of [part] which does not exist in its owning entity class [class com.adityas.jpa.masters.packageParts.MPackageparts]. If the owning entity class is a @MappedSuperclass, this is invalid, and your attribute should reference the correct subclass.
         at oracle.toplink.essentials.exceptions.ValidationException.noMappedByAttributeFound(ValidationException.java:1118)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataValidator.throwNoMappedByAttributeFound(MetadataValidator.java:297)
         at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.RelationshipAccessor.getOwningMapping(RelationshipAccessor.java:127)

    @Entity
    @Table(name = "m_part", catalog = "dms_dev")
    public class MPart implements java.io.Serializable {
         // Fields
         private static final long serialVersionUID = -7784550511312653300L;
         private Integer partPk;
         private MWarehouse warehouse;
         private String partNo;
         private String venderPartNo;
         private String partName;
         private Integer group2;
         private Integer issueUom;
         private Integer purchaseUom;
         private String warrantyAppl;
         private String returnable;
         private String salvageValue;
         private Double mrp;
         private Double ndp;
         private Double venderPrice;
         private String partLocation;
         private Double stockInHand;
         private Double minQty;
         private Double openQty;
         private String decsription;
         private Integer crtBy;
         private Date crtDt;
         private Integer updBy;
         private Date updDt;
         private Integer partGroup;
         private Set<TReqApprDtl> reqApprDtls = new HashSet<TReqApprDtl>(0);
         private Set<TPcrInfo> pcrInfos = new HashSet<TPcrInfo>(0);
         private Set<TPoReceive> poReceives = new HashSet<TPoReceive>(0);
         private Set<MPackageparts> packagepartses = new HashSet<MPackageparts>(0);
         private Set<TPoReturn> poReturns = new HashSet<TPoReturn>(0);
         private Set<TAncillaryDtls> ancillaryDtlses = new HashSet<TAncillaryDtls>(0);
         private Set<TPoDetails> poDetailses = new HashSet<TPoDetails>(0);
         // Constructors
         /** default constructor */
         public MPart() {
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "part")
         public Set<MPackageparts> getMPackagepartses() {
              return this.packagepartses;
         public void setMPackagepartses(Set<MPackageparts> packagepartses) {
              this.packagepartses = packagepartses;
    @Entity
    @Table(name = "m_packageparts", catalog = "dms_dev")
    public class MPackageparts implements java.io.Serializable {
         // Fields
         private static final long serialVersionUID = -3528271808797143260L;
         private Integer packagePartPk;
         private MPart part;
         private MComplaint complaint;
         private Double reqQuantity;
         private Integer crtBy;
         private Date crtDt;
         private Integer updBy;
         private Date updDt;
         // Constructors
         /** default constructor */
         public MPackageparts() {
    @ManyToOne(fetch = FetchType.EAGER)
         @JoinColumn(name = "PART_PK", nullable = false)
         public MPart getMPart() {
              return this.part;
         public void setMPart(MPart part) {
              this.part = part;
    Yes it is mentioned as ManyToOne mapping.

  • JPA OnetoMany  QUERY LEFT JOIN BUG

    Using JPA in JDev 10.1.3.1.0.3984
    Database: Firebird 1.51LI-V1.5.3.4870 Firebird 1.5/tcp
    Driver: Jaybird JCA/JDBC driver Version: 2.1
    TopLink, version: Oracle TopLink Essentials - 2006.8 (Build 060829)
    If I use normal JOIN it works.
    On LEFT JOIN I get a {oj [/b] before the table name and a [b]} at the end.
    public class Cliente{
        @OneToMany(mappedBy = "cliente")
        @JoinColumn(name = "CDCLIENTE", referencedColumnName = "CDCLIENTEREQUISITANTE")
        private List<Requisicao> requisicoes;
    public class Requisicao
        @ManyToOne
        @JoinColumn(name = "CDCLIENTEREQUISITANTE", referencedColumnName = "CDCLIENTE")
        private Cliente cliente;
    EntityManager em = getEntityManager();
    String sql = "SELECT c FROM Cliente c LEFT JOIN c.requisicoes req";
    Query q = em.createQuery(sql);
    List rs = q.getResultList();Result SQL:
    SELECT DISTINCT t0. <OMITTED> FROM {oj [/b]CLIENTE t0 LEFT OUTER JOIN REQUISICAO t1 ON (t1.CDCLIENTEREQUISITANTE = t0.CDCLIENTE)[b]}

    You cannot define an ON clause with Criteria, nor JPQL.
    Perhaps you can reword the query to avoid needing an ON clause.
    What is the query you want to do (in english)?
    Can you just use an OR in the where clause?
    There is a enhancement request to have ON clause support added, please vote for it.
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=312146
    James : http://www.eclipselink.org

  • Map XMLTyp Toplink Essentials

    hi,
    I'm been looking up info for a while now about XMLType. I found out that Toplink Essentials not directly supports XMLType but I managed to get it from the database. When I have got the object as an oracle.xdb.XMLType then I can read it, which is good, but now (when I alter it) i have to store it again. I use this to alter my XMLType:
        public static void main(String[] args) throws Exception{
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("data");
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            WebeMakrArtikel wma = (WebeMakrArtikel) em.find(WebeMakrArtikel.class, 1L);
            String newXmlString = "<newXml></newXml>";
            XMLType xml = wma.getArtikelXml();
            XMLType newXml = XMLType.createXML(xml.getJavaSqlConnection(), newXmlString);
            wma.setArtikelXml(newXml);       
            em.getTransaction().commit();
            em.close();
            emf.close();
        }But then i get this error :
    Exception in thread "main" javax.persistence.RollbackException: java.lang.NullPointerException
         at oracle.toplink.essentials.internal.ejb.cmp3.transaction.base.EntityTransactionImpl.commit(EntityTransactionImpl.java:109)
         at oracle.toplink.essentials.internal.ejb.cmp3.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:45)
         at be.roularta.schrijf.Main.main(Main.java:19)
    Caused by: java.lang.NullPointerException
         at oracle.sql.Datum.equals(Datum.java:65)
         at oracle.toplink.essentials.mappings.foundation.AbstractDirectMapping.compareObjects(AbstractDirectMapping.java:286)
         at oracle.toplink.essentials.mappings.foundation.AbstractDirectMapping.compareForChange(AbstractDirectMapping.java:219)
         at oracle.toplink.essentials.descriptors.changetracking.DeferredChangeDetectionPolicy.createObjectChangeSetThroughComparison(DeferredChangeDetectionPolicy.java:124)
         at oracle.toplink.essentials.descriptors.changetracking.DeferredChangeDetectionPolicy.createObjectChangeSet(DeferredChangeDetectionPolicy.java:103)
         at oracle.toplink.essentials.descriptors.changetracking.DeferredChangeDetectionPolicy.calculateChanges(DeferredChangeDetectionPolicy.java:81)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.calculateChanges(UnitOfWorkImpl.java:476)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1108)
         at oracle.toplink.essentials.internal.ejb.cmp3.base.RepeatableWriteUnitOfWork.commitRootUnitOfWork(RepeatableWriteUnitOfWork.java:82)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.commitAndResume(UnitOfWorkImpl.java:842)
         at oracle.toplink.essentials.internal.ejb.cmp3.transaction.base.EntityTransactionImpl.commit(EntityTransactionImpl.java:90)
         ... 2 moreCan anyone help me to store this XMLType back in the database?
    Why does XMLType keep the connection anyway?

    XMLType is supported by EclipseLink which is replacing TopLink Essentials as the JPA implementation in GlassFish V3 and will be shipped in OracleAS/TopLink 11gR1. In addition to mapping XMLType columns into XML Strings or DOMs in the domain model the support also includes expression support so that
    SQLX queries can be generated.
    The solution in EclipseLink involves several classes working together to handle all of the reading, writing and querying capabilities so it not easy to point at a single piece of code to solve your problem.
    Doug

  • Auto-mapping in Toplink

    how can TopLink's auto-mapping feature be coded if my application was deployed as a Java project?
    the mapping information/descriptors (and all that) are in a java file. I am about to add 2 new fields to my database table, and would like to use TopLink's auto-map feature. Problem is, I don't have the workbench GUI interface.
    I have instructions (thanks to Don) on how to map by hand-coding, but if there is a setting that I can code, say a one-liner or so, that would be great.

    I think there is a misunderstanding as to what a persistence layer is and does... To update your application with new state, you need to first update your object model (has nothing to do with TopLink), then your application (again, nothing to do with TopLink), and then your mappings and persistence layer code (has to do with TopLink). There is no magic here.
    Auto-mapping is a feature in the Mapping Workbench to do much of the tedious O-R mapping automatically. It does not automatically keep your application up to date with schema chages.
    - Don

  • Mapping in TopLink workbench: Sorting order for one-to-one mapping field

    Hi,
    we have a requirement; though it is one-to-many relationship, we wanted to map it as one-to-one, so that we get latest of the mappped entity based on attribute:*noOfVisits*. For this, I am trying to make descending order by noOfVisists in workbench; but no provision there.. it is available only for one-to-many relationship;
    If I map as one-to-many, I can specify the sorting order; but is there any option to limit the max rows of it to *1*.
    Pls suggest the solution; I am trying to avoid to write named query for this; and wanted to get from the entity itself by navigating to one-to-one relationship entity.
    Thanks,
    Dhana kumar.

    Hello,
    If you want strictly JPA options, I'd either not map it and query for it (which you can then store it in the object if you want in a transient attribute), or map it as 1:M with the order by and have a getSingleVistedChild type method that returns the first element if its noOfVisits value is 1.
    Mapping it using the 1:1 as you are asking can be done. All that is required is that you add selection criteria for the query used in the mapping as described here:
    http://wiki.eclipse.org/EclipseLink/Examples/JPA/MappingSelectionCriteria
    Best Regards,
    Chris

  • Dynamic Query Mapping using Toplink Entity

    Hi,
    We have a requirement that the column names of the table dynamically gets changed for different customers.
    eg;
    Client 1 , will have
    Select EMP_ID, EMP_NAME from EMPLOYEE
    Client 2 will have
    SELECT CEMP_ID, EMP_NAME, CEMP_ADDR from EMPLOYEE
    Is it possible to make a Toplink Entity Employee object to support both the queries at runtime ?ie; we should not modify the java entity object for each customer.
    With normal JDBC , we can perform SELECT * from EMPLOYEE ,get the resultset , and using metadata , we can find the column names and process it accordingly.
    Is this functionality possible with toplink JPA at all ?
    Thanks
    prabu

    Hi,
    I am trying to use DynamicEntity class. Is Joined Table Inheritance supported in DynamicEntity ? Since I need to create an HybridEntity on the fly by selecting all the fields from TABLE A and TABLE B by joining key fields, whose fields will dynamically change based upon the customer. Below is what I am currently trying to do. But the Entity Object that I got contains fields only from TABLE A and not from TABLE B
    EntityManagerFactory emf = new EntityManagerFactoryImpl(setup,EclipseLinkJPATest.getEMFProperties());
    SchemaManager manager = new SchemaManager(JpaHelper.getServerSession(emf));
    Vector <DatabaseRecord>tableAEntityFieldNames = manager.getAllColumnNames("TABLE A");
    Vector <DatabaseRecord>tableBFieldNames = manager.getAllColumnNames("TABLE B");
    EntityType tableAType = EntityTypeFactory.create("TableAEntity","DynamicEntity$TableAEntity", "TABLE A", loader);
    String columnName = null;
    for(DatabaseRecord tableAObj: tableAEntityFieldNames){
    columnName = tableAObj.get("COLUMN_NAME").toString();
    EntityTypeFactory.addBasicProperty(tableAType, columnName, columnName,
    "TABLE A_ID".equals(columnName) ? Long.class : String.class, "TABLE A_ID".equals(columnName) ? true : false);
    EntityTypeFactory.addToPersistenceUnit(emf, tableAType);
    EntityType stepType = EntityTypeFactory.create("TableBEntity","DynamicEntity$TableBEntity", "TABLE B", loader);
    for(DatabaseRecord tableBObj: tableBEntityFieldNames) { 
    columnName = tableBObj.get("COLUMN_NAME").toString();
    EntityTypeFactory.addBasicProperty(tableBType, columnName, columnName,"TABLE B_ID".equals(columnName) ? Long.class : String.class, "TABLE B_ID".equals(columnName) ? true : false);
    EntityTypeFactory.addToPersistenceUnit(emf, tableBType);
    EntityManager em = emf.createEntityManager();
    List <DynamicEntity> entityList = null;
    entityList = em.createQuery("select s from TableAEntity s, TableBEntity st where s.TABLE A_ID= st.TABLE B_IDand s.TABLE A_ID=?1")
              .setParameter(1, 1397)
              .getResultList();
    System.out.println("entityList..."+entityList);
    Thanks
    Prabu

  • Why migrate from toplink 10.1.2 to EJB 3 JPA instead of to toplink 10.1.3?

    We're in the situation that we're using Toplink 10.1.2 and are making plans for our next release. I'm wondering wether we should 'just' migrate to the 10.1.3 version of the Toplink API or wether we should migrate to EJB 3.0 JPA API (with Toplink as implementation).
    Advantages and drawbacks I see are the following:
    Toplink API 10.1.3 versus EJB 3 Persistency on Toplink
    + maybe the only way to access Toplink specific functionality: i.e. historic queries. (Is that a fact by the way?)
    - In the long run it will be easier to hire people with knowledge of EJB 3.0 Persistency
    + Maybe smaller effort to migrate. (Is that true? I guess we'd have to add a lot of annotations)
    Are there more drawbacks/advantages?
    Regards,
    Joost de Vries
    Netherlands

    Hasam,
    We do have a uix to JSF migration utility that you can get through the check for update center. The missing part there right now is that it doesn't support uix template migration.
    If you are using jheadstart you might want to post your question on the jheadstart forum as well they might be able to do the migration through their repository.
    And remember that if your application is working now and your customers are happy then you don't have to migrate it.

  • JPA OneToMany bidirectional -- Entity deletion

    I am having trouble deleting an entity part of a part-whole hierarchy and mapped as a OneToMany bidirectional relationship. For example:
    public class A {
        @OneToMany(mappedBy="parent", cascade={CascadeType.MERGE, CascadeType.PERSIST})
        private Collection<A> children;
        @ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
        @JoinColumn(name="PARENT_ID")
        private A parent;
    }Instances of 'A' can, but do not HAVE to participate in this relationship. Therefore, a cascade on remove is not appropriate, because for any given instance of 'A', a parent and/or any of the children can exist independent of that instance.
    So basically I want to remove an instance of 'A', and at the same time have it's child relationships updated -- basically pointing to a null parent.
    What's the proper way to do this?
    The first and most obvious way to me is:
        entityManager.remove(instanceOfA);But that results in the cryptic error: "deleted entity passed to persist".
    The only way I've gotten this to work so far is to use two transactions. In the first, I simply break the relationships and merge the objects:
        Collection<A> children = instanceOfA.getChildren();
        instanceOfA.setChildren(null);
        for(A child : children) {
            child.setParent(null);
            entityManager.merge(child);
        entityManager.merge(instanceOfA);And in the second transaction:
        instanceOfA = entityManager.find(A.class, instanceOfA.getId());
        entityManager.remove(instanceOfA);This works, but feels very clunky.
    What is the proper way to do this?
    Thanks,
    Justin

    I am having trouble deleting an entity part of a part-whole hierarchy and mapped as a OneToMany bidirectional relationship. For example:
    public class A {
        @OneToMany(mappedBy="parent", cascade={CascadeType.MERGE, CascadeType.PERSIST})
        private Collection<A> children;
        @ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
        @JoinColumn(name="PARENT_ID")
        private A parent;
    }Instances of 'A' can, but do not HAVE to participate in this relationship. Therefore, a cascade on remove is not appropriate, because for any given instance of 'A', a parent and/or any of the children can exist independent of that instance.
    So basically I want to remove an instance of 'A', and at the same time have it's child relationships updated -- basically pointing to a null parent.
    What's the proper way to do this?
    The first and most obvious way to me is:
        entityManager.remove(instanceOfA);But that results in the cryptic error: "deleted entity passed to persist".
    The only way I've gotten this to work so far is to use two transactions. In the first, I simply break the relationships and merge the objects:
        Collection<A> children = instanceOfA.getChildren();
        instanceOfA.setChildren(null);
        for(A child : children) {
            child.setParent(null);
            entityManager.merge(child);
        entityManager.merge(instanceOfA);And in the second transaction:
        instanceOfA = entityManager.find(A.class, instanceOfA.getId());
        entityManager.remove(instanceOfA);This works, but feels very clunky.
    What is the proper way to do this?
    Thanks,
    Justin

  • ObjectRelational Mapping with Toplink

    Hi,
    I'm looking for any tutorial or example about ObjectRelational mappings, Object-types, Varrays, Nested tables, ObjectRelationalDescriptor. I tried with code examples from b100063,b100064. but they are too short and not clear.
    thanks,

    Hi,
    I found this example on metalink.oracle.com it gives a good example of a Varray. I tried the example and it works. You said that there were code examples: b100063,b100064, where are they located.
    Anyway here is the example:
    Bookmark Fixed font Go to End
    Doc ID: Note:224177.1
    Subject: Mapping to a VARRAY object type defined in an Oracle database
    Type: SAMPLE CODE
    Status: PUBLISHED
    Content Type: TEXT/PLAIN
    Creation Date: 20-DEC-2002
    Last Revision Date: 08-APR-2003
    Overview
    Oracle9iAS TopLink supports object-relational mapping. That means that
    custom made datatypes (created by developer) in database could be used
    to map some java application side attributes to. One of object types is
    VARRAY. Mapping Workbench does not allow object-relational mapping (at
    the time when this article is written), but if this feature is needed,
    project file can be edited to accomplish this.
    If object type (VARRAY) already exist in database, all developer has to
    do is make TopLink aware of it and map an attribute to it.
    Program Notes
    This example uses varray type courses_list_type defined in oracle database as:
    create or replace type courses_list_type as varray(5) of varchar2(25);
    The courses_list_type type is used in table test_student (used in this example)
    defined as:
    create TABLE test_student (
    student_id number(3) PRIMARY KEY,
    student_name varchar2(30),
    student_courses courses_list_type);
    Since we need some data in table test_student, the following statement has
    been executed:
    INSERT INTO test_student VALUES(1, 'Ron More',
    courses_list_type ('Visual Basic', 'Java', 'C++', 'UML', 'SQL'));
    Caution
    The sample program in this article is provided for educational purposes only
    and is NOT supported by Oracle Support Services. It has been tested
    internally, however, and works as documented. We do not guarantee that it
    will work for you, so be sure to test it in your environment before relying
    on it.
    Program
    SessionEventAdapter class must be set up and the preLogin() method implemented.
    The session can be retrieved from the SessionEvent (getSession() method) and
    descriptor with the VARRAY MAPPING (the new ObjectRelationalDescriptor) added
    to the project. This must be done in code since this cannot be done from the
    Mapping Workbench. This is recommended way of dealing with this issue since
    the modification of the project.java (generated by Mapping Workbench) file is
    avoided. Doing this, project itself can be modified many times without changing
    object-relational descriptor.
    A) class Student is created in Jdeveloper
    package oracle.toplink.demos.employee.domain;
    import java.util.*;
    import java.io.*;
    public class Student {
    private int id;
    private String name; // a collection of courses being stored in Oracle database as VArray type
    private Vector courses;
    public Student ( ){
    this.id = 0;
    this.name = "";
    this.courses = new Vector(5);
    public void addCourse(String courseName){getCourses().addElement(courseName);}
    public void removeCourse(String courseName){getCourses().removeElement(courseName);}
    public int getId ( ) {return id;}
    public String getName ( ) {return name;}
    public Vector getCourses(){ return courses;}
    public void setId(int studentId) {this.id = studentId;}
    public void setName(String studentName) {this.name = studentName;}
    public void setCourses(Vector studentCourses){this.courses = studentCourses;}
    } // end of class student
    B) implementation of SessionEventAdapter class
    package oracle.toplink.demos.employee.domain;
    import oracle.toplink.sessions.*;
    import oracle.toplink.demos.employee.relational.*;
    public class MySessionEventAdapter extends SessionEventAdapter{
    /* This Event is raised before the session logs in. */
    public void preLogin(SessionEvent event){
    System.out.println("In preLogin()");
    // need empProject variable since it owns the buildStudentDescriptor() method
    EmployeeProject empProject = new EmployeeProject();
    event.getSession().getProject().addDescriptor(empProject.buildStudentDescriptor());
    } // end of preLogin
    } // end of MySessionEventAdapter
    Before login to database the following two lines must be executed:
    MySessionEventAdapter myAdapter = new MySessionEventAdapter();
    session.getEventManager().addListener((SessionEventListener)myAdapter);
    C) method that builds the ObjectRelationaDescriptor descriptor on student class
    public static Descriptor buildStudentDescriptor(){
    ObjectRelationalDescriptor descriptor = new ObjectRelationalDescriptor();
    descriptor.setJavaClass(oracle.toplink.demos.employee.domain.Student.class);
    descriptor.setTableName("TEST_STUDENT");
    descriptor.setPrimaryKeyFieldName("TEST_STUDENT.STUDENT_ID");
    // Mappings.
    DirectToFieldMapping idMapping = new DirectToFieldMapping();
    idMapping.setAttributeName("id");
    idMapping.setFieldName("TEST_STUDENT.STUDENT_ID");
    descriptor.addMapping(idMapping);
    DirectToFieldMapping nameMapping = new DirectToFieldMapping();
    nameMapping.setAttributeName("name");
    nameMapping.setFieldName("TEST_STUDENT.STUDENT_NAME");
    descriptor.addMapping(nameMapping);
    ArrayMapping coursesMapping = new ArrayMapping(); // here we do not use ObjectArrayMapping
    coursesMapping.setAttributeName("courses");
    coursesMapping.setGetMethodName("getCourses");
    coursesMapping.setSetMethodName("setCourses");
    coursesMapping.setStructureName("COURSES_LIST_TYPE");
    coursesMapping.setFieldName("TEST_STUDENT.STUDENT_COURSES");
    descriptor.addMapping(coursesMapping);
    return descriptor;
    } // end of buildStudentDescriptor()
    Defining the student descriptor this way, TopLink has all information on varray
    type used. Please note that varray type already exist in database so ArrayMapping
    is used instead of ObjectArrayMapping.
    D) method that inserts object of type student into database
    public void callObjectRelationalVArray(){
    session.initializeIdentityMaps();
    System.out.println("\n\n\nSTART: callObjectRelationalVArray()");
    /* ************* callObjectRelationalVArray; insert student - start *******/
    UnitOfWork uowInsertStudent = session.acquireUnitOfWork();
    Student newStudent = new Student();
    Student cloneStudent = (Student)uowInsertStudent.registerObject(newStudent);
    cloneStudent.setId(6);
    cloneStudent.setName("Ron Moore");
    cloneStudent.addCourse("Java");
    cloneStudent.addCourse("JBuilder");
    cloneStudent.addCourse("HTML");
    cloneStudent.addCourse("Rational Rose");
    cloneStudent.addCourse("Visual Basic");
    uowInsertStudent.commit();
    /* ************* callObjectRelationalVArray; insert student - end *********/
    System.out.println("END: callObjectRelationalVArray()");
    } // end of callObjectRelationalVArray
    Sample Output
    By executing callObjectRelationalVarray() method JDeveloper produces the
    following output:
    START: callObjectRelationalVArray()
    DatabaseSession(11)--Connection(12)--delete test_student where STUDENT_ID = 6
    student with STUDENT_ID = 6 is deleted
    DatabaseSession(11)--acquire unit of work:28
    UnitOfWork(28)--begin unit of work commit
    DatabaseSession(11)--Connection(12)--begin transaction
    UnitOfWork(28)--Connection(12)--INSERT INTO TEST_STUDENT
    (STUDENT_ID, STUDENT_NAME, STUDENT_COURSES) VALUES (?, ?, ?)
    bind => [6, Ron Moore, oracle.sql.ARRAY@20]
    DatabaseSession(11)--Connection(12)--commit transaction
    UnitOfWork(28)--end unit of work commit
    UnitOfWork(28)--release unit of work
    Copyright (c) 1995,2000 Oracle Corporation. All Rights Reserved. Legal Notices and Terms of Use.

Maybe you are looking for