One to Many Again :(

The problem that we currently have is to do with One-To-Many mappings. 1:1 and M:M work perfectly well. Only 1:M relations are not working properly the way we anticipate it to work.
Consider the example:
PurchaseOrder and LineItems. Each purchase order might have more than one LineItem and so PurchaseOrder class will have a list of LineItems and we map this list using 1:M mapping within the workbench.
Toplink Behavior:
In case of insert the foreign key in the child record is null and so it fails to insert.
And some forums suggested that we have a backward relation. ie the child object should contain a parent object, which my opinion is very wrong because we are not really achieving 1:M relation, rather we are doing many 1:1 relations. Moreover having a parent object in the child and each parent having a list to me sounds like it might end-up in a circular reference ??
Has anybody had any luck setting up 1:M properly without backward relation? Please share your experiences and workarounds.
Regards,
Murali

Murali,
Our FAQ covers this briefly listing alternatives:
http://www.oracle.com/technology/products/ias/toplink/technical/tl10g_faq.htm#OneToOneBack
I strongly recommend mapping all FKs as 1:1. In an ORM system these are actually the governing relationships and the 1:M are the optional associations. Mapping the 1:1 back-ref will create a much needed circular reference, which is easily managed in the model.
The other options provided are also completely supported but will not provide the flexibility and performance of the 1:M + 1:1 solution.
This approach is in line with all leading ORM solutions and is what you will find in the upcoming EJB3 specification as well.
Cheers,
Doug

Similar Messages

  • From MS Access One-to-Many Form to Oracle Express

    Hello, hello,
    Firstly, I am new at Oracle and interested to really getting into out, however, I am a little ancy to get going. I'm looking for some sharp direction that could direct me to exactly what I need to do right now and then I can do further study, etc.
    I have a MS Access database with many tables, queries, etc. But I set up a fancy form whereby I could scroll to the name (let's say EMPLOYEE) and then I have about 10 different forms (a tabbed interface because there were so many) show up where I could input data about that employee specifically. Then when I scroll to the next person, all of the subforms would change accordingly.
    Thus, ultimately, what I would like to do using Oracle Express and APEX is to set up a page where I have a region which will pull a list of employees and act as a menu, then when someone select an employee (i.e., not only me) then all information, from numerous different tables pulls up and is visible, editable and can be added to. There could be a region for addresses, a region for links, for notes, for photos, for a list of articles, or whatever.
    I hope you track with what I am looking at. In Access I have numerous tables, then I create a monstrous one-many relationship thingamajiggy and ka-boom, things all fit together in a form, and subforms. All editable by me, but hardly available for anyone else. I know Oracle is the way to go, so...
    Can you assist me by explaining what I need to implement in Oracle? I am not clear on JOINs and what's the right one to use, how to adequately connect all of the dots, etc. Do I need to set up fancy queries, create SQL statements or what?
    Thanks.

    Thanks. I don't think my question is strictly APEX related.
    Rather, I am trying to determine how to create a "one-to-many" relationship (to use MS Access terminology) in Oracle Express. And then solve how to add data to them.
    I can create a view which links two tables together where I can add data, but I want to be able to be adding data to several tables all linked together from the same primary key. One row per person (or employee) won't handle this, particularly if you want to add more than one row of data about the person in a table.
    For example, if I had a restaurant with four employees (a cook, a waitress, a baker and a cleaner), my employees table would only have four rows. But now if I wanted to record the types of desserts the baker could make, that would take up more than one row. Therefore, from the baker, it would have to link to another table where I could input data about the different desserts. Typical one-to-many relationship. But the baker can also make different kinds of bread, thus another table with several rows. Perhaps the baker is so good, I may want to have yet another table for his different supremely delicious and famous pies (apple, pumpkin, pecan, etc.) which is now another table. The options are endless, but they all connect to the baker.
    As a result, someone could come to my application and ask what can the baker do, and it will pull up a table of desserts, a table of pies and a table of breads.
    Once I figure that out and can link many tables together using one primary key, then I presume I can easily move into the web application aspect. But for now, I am not quite there yet.
    If someone can at least direct me as to what this is called in Oracle and give me a little direction, then I will feel more confident in moving forward. Thanks again!

  • 3 way one-to-many through a single link table

    I have 3 tables that are linked through one to many relationships in a single link table. Here's the real relationships:
    assay(id)
    multiplex(id, assays)
    markerset(id, assays, multiplexes)
    Here's the database schema:
    assay(id, name)
    markerset(id, name)
    multiplex(id, name)
    assay_marker_set(assay_id[not null], marker_set_id[not null], multiplex_id[nullable])
    I've mapped one-to-many relationships between markersets and assays, and multiplexes and assays, and BOTH of these one-to-manys need to be writable. In the record creation process, assays are associated with markersets, and then assays are associated with multiplexes, which in turn are associated with markersets.
    Here's our dilemma. When committing multiplexes through a unit of work, the one-to-many with assays can't see the one-to-many with markersets, so the commit fails because the markerset key is null.
    We've gotten around the problem by creating a postSave() method in markerset that writes multiplex changes once they are created. But again, in a unitofwork commit, saving a markerset fires the postSave() method, which writes assays and multiplexes that have not yet been written to the database.
    We've gotten around THAT by only turning on postSave() when creating multiplexes, not when associating assays with markersets.
    My question is, is there a more conventional approach to this problem? Clearly, the database needs to be reworked, but time constraints and the quantity of data to be curated makes changing the schema impossible. Or have we arrived at the most sensible solution to a ridiculous problem? Currently what we have works, it's just incredibly complicated, and nearly unmaintainable.
    Thanks for the time to even read this post, and mocking is permitted ;-)
    Paul Cooper
    GlaxoSmithKline US Bioinformatics

    Looks like your object model does not match your data model.
    From you object model you seem to have,
    Assay
    MarkerSet 1-m Assay, 1-m Multiplex
    Multiplex 1-m Assay
    From your data model you have,
    Assay 1-m AssayMarkerSetAssociation
    MarkerSet 1-m AssayMarkerSetAssociation
    Multiplex 1-m AssayMarkerSetAssociation
    AssayMarkerSetAssociation 1-1 Assay, 1-1 MarkerSet, 1-1 Multiplex
    (your object model seems to be also missing the name)
    I'm not exactly sure how you have your mapping working, but it would seem the best solution is to introduce an AssayMarkerSetAssociation object into your object model.
    If you do not wish to use this object in your model, you could just use it internally to store the relationship and still have get/set methods for the relationships that you want that initialize themselves from the associations.
    So your object model would be,
    Assay
    MarkerSet 1-m AssayMarkerSetAssociation (+ getAssays, getMultiplexes methods)
    Multiplex 1-m AssayMarkerSetAssociation (+ getAssays, method)
    AssayMarkerSetAssociation 1-1 Assay, 1-1 MarkerSet, 1-1 Multiplex
    In general you seem to be able to get your mapping working without changing your object model, but are probably better off for maintainability to change your model slightly.

  • 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

  • One to many relationships in EJB

    I have two EBs related by a one to many relationship. The first of these tables is called Student and has studentId as its key. The second of the tables has a composite key made up of studentID, courseID and semesterID.
    However, when the tables are generated in NetBeans 5.5, I find that the Course table has studentID as both a primary key and a foreign key.
    I am at a loss to understand this as I am new to NetBeans and EJB.
    Can anyone advise?
    Thanks
    Martin O'Shea.
    The Student class:
    package CBSD_CW;
    import java.io.Serializable;
    import javax.persistence.*;
    import java.util.*;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    @Entity
    public class Student_EB implements Serializable {
        // Table columns.
        @Id
        @Column(name = "STUDENT_ID", nullable = false)
        private Long studentId; // Student ID. Entity <Student><ID> from file: SampleData.xml.
        @Column(name = "FIRST_NAME", length = 50, nullable = true)
        private String firstName; // First Name. Entity <Student><FirstName> from file: SampleData.xml.
        @Column(name = "LAST_NAME", length = 50, nullable = true)
        private String lastName; // Last Name. Entity <Student><LastName> from file: SampleData.xml.
        @Column(name = "STUDENT_LEVEL", length = 2, nullable = true)
        private String studentLevel; // Student Level. Entity <Student><Level> from file: SampleData.xml.
        @Column(name = "PROGRAM_NAME", length = 50, nullable = true)
        private String programName; // Program Name. Entity <Student><ProgramName> from file: SampleData.xml.
        @Column(name = "PROGRAM_NUMBER", length = 3, nullable = true)
        private String programNumber; // Program Number. Entity <Student><ProgramNumber> from file: SampleData.xml.
        // 1:M relationship with Course_EB.
        @OneToMany(cascade=CascadeType.ALL, mappedBy="student")
        private List<Course_EB> courses;
        public List<Course_EB> getCourses() {
           return courses;
        public void setCourses(List<Course_EB> courses) {
           this.courses = courses;
        // Accessors and mutators.
        public Long getId() {
            return this.studentId;
        public void setId(Long studentId) {
            this.studentId = studentId;
        public String getFirstName() {
            return firstName;
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        public String getLastName() {
            return lastName;
        public void setLastName(String lastName) {
            this.lastName = lastName;
        public String getStudentLevel() {
            return studentLevel;
        public void setStudentLevel(String studentLevel) {
            this.studentLevel = studentLevel;
        public String getProgramName() {
            return programName;
        public void setProgramName(String programName) {
            this.programName = programName;
        public String getProgramNumber() {
            return programNumber;
        public void setProgramNumber(String programNumber) {
            this.programNumber = programNumber;
        // Other methods.
        public boolean equals(Object obj) {
           if (obj == this) {
               return (true);
           if (!(obj instanceof Student_EB)) {
               return (false);
           if (obj == null) {
               return (false);
           Student_EB student = (Student_EB) obj;
           return (student.studentId == studentId);
    The Course class:
    package CBSD_CW;
    import javax.persistence.CascadeType;
    import javax.persistence.EmbeddedId;
    import javax.persistence.Entity;
    import javax.persistence.JoinColumn;
    import javax.persistence.JoinTable;
    import javax.persistence.ManyToOne;
    @Entity
    public class Course_EB implements java.io.Serializable {
       Course_PK course;
       // M:1 relationship with Student_EB.
       private Student_EB student;
       @ManyToOne(cascade=CascadeType.ALL)
       @JoinTable(name = "Student_EB", joinColumns= @JoinColumn(name = "STUDENT_ID", referencedColumnName = "studentId"))
       public Student_EB getStudent() {
          return (student);
       public void setStudent(Student_EB student) {
          this.student = student;
       // Constructor.
       public Course_EB() {
       // Accessors and mutators.
       @EmbeddedId
       public Course_PK  getCourse_PK () {
          return (course);
       public void setCourse_PK(Course_PK course) {
          this.course = course;
    The Course_PK class:
    package CBSD_CW;
    import javax.persistence.Column;
    import javax.persistence.Embeddable;
    @Embeddable
    public class Course_PK implements java.io.Serializable {
       // Table columns.
       @Column(name = "STUDENT_ID", length = 4, nullable = false)
       private long studentId; // Student ID. Entity <Student><ID> from file: SampleData.xml.
       @Column(name = "COURSE_ID", length = 4, nullable = false) 
       private String courseId; // Course ID. Entity <Student><Course><Number> from file: SampleData.xml.
       @Column(name = "SEMESTER_CODE", length = 3, nullable = false)
       private String semesterCode; // Semester Code. Entity <Student><Course><SemesterCode> from file: SampleData.xml.
       @Column(name = "GRADE", nullable = true)
       private char grade; // Grade. Entity <Student><Course><Grade> from file: SampleData.xml.
       // Constructors.
       public Course_PK() {
       public Course_PK(long studentId, long courseid, String semesterCode) {
          this.studentId = studentId;
          this.courseId = courseId;
          this.semesterCode = semesterCode;
       // Accessors and mutators.
       public long getStudentId() {
          return (studentId);
       public void setStudentId(long studentId) {
          this.studentId = studentId;
       public String getCourseId() {
           return (courseId);
       public void setId(String courseId) {
           this.courseId = courseId;
       public String getSemesterCode() {
           return (semesterCode);
       public void setSemesterCode(String semesterCode) {
           this.semesterCode = semesterCode;
       public char getGrade() {
           return (grade);
       public void setGrade(char grade) {
           this.grade = grade;
       // Other methods.
       public boolean equals(Object obj) {
           if (obj == this) {
               return (true);
           if (!(obj instanceof Course_PK)) {
               return (false);
           if (obj == null) {
               return (false);
           Course_PK course = (Course_PK) obj;
           return ((course.studentId == studentId) &&
                   (course.courseId.equals(courseId)) &&
                   (course.semesterCode.equals(semesterCode)) &&
                   (course.grade == grade));
    }

    Because you have field
    @Column(name = "STUDENT_ID", length = 4, nullable = false)
       private long studentId; // Student ID. Entity <Student><ID> from file: SampleData.xml.In you Course_PK class. As a primary keys.
    An again you are joining it in field
        @ManyToOne(cascade=CascadeType.ALL)
       @JoinTable(name = "Student_EB", joinColumns= @JoinColumn(name = "STUDENT_ID", referencedColumnName = "studentId"))So it is appearing both inPrimary Key and in Foreign Key.

  • Merge Two Reports in Excel Analyzer - One To Many Relationship

    I want to show AR Data with CO Data - e.g. a bill + Income and it's associated account ssignemnt on the FI/CO side. I want the report to be able to show a cost centre manager to be wary of the income credited to their cost centre when a debtor has been raisedaas they may not fully pay the bill. To do this I'm using the standard DSO for AR & GL line items. Fisrtly I run a query on GL line item data where the user can select from a cost centre variable to look at credits to their cost centre. This produces a list of source documents that are used (via replacement path variable) in a second query. The second GL Query gives me a list of the allocation numbers for those line items. Had to be two queres as there are two GL postings that needed linking (this is because the cost assignment comes from a ceratin acc type and the debtor information comes from another acc type). I then use the allocation number (again via a replacement path variable) to run a third query on the AR data that shows all bills and payments linked to that allocation number. It seems to work ok.
    However I have put these three queries in an Excel Analyzer workbook. All the user does is enter a cost centre when running the report. Each query is on a different sheet but what I'd like to do is merge the data on to the one sheet. I want to see the bill and it's payments from the AR data matched up with the cost assignment from the FI/CO data. This would be a one to many relationship e.g. one bill may have it's cost assignment split over more than one cost centre. Is there anyway to do this using simple excel functionality?
    So I'd like to see:
    Allocation No. 12345 Bill £100 Revenue £50 Cost Centre 1234 £25
                                                                           Cost Centre 2345 £25
    Anybody any ideas?

    Hi,
    Thanks for your answers.
    I did explore using infosets but really struggled with joining the data and getting a sensible output. For example where a bill was done in installments I was getting 12 lines (e.g. one for each month) rather than just one. THis meant it looked liked they'd paid twleve times as much etc.
    I did also try report to report. Which to my mind worked ok. Except the customer wanted it all in "One" report rather than having to drill down to see data.
    I'll try a multiprovider but I'm worried that I'll end up with similar issues as I had when using the infoset.
    Cheers
    Joel

  • Messy One to Many Joins and Grouping

    I manage websites for a large state agency in Texas. I have a
    need to redo
    queries that list the Local intake numbers for Long term
    support services
    (LTSS), Area Agencies on Aging (AAA), and Mental Retardation
    Authorities
    (MRA) by county for each of the state's 254 counties -- in
    the past there
    was only one intake number per county for each AAA and MRA,
    with there being
    the possibility for multiple LTSS intake numbers. Now there
    are counties
    that have multiple numbers for MRA intake.
    Basic Structure of Database Tables:
    CountyCenter Table
    County (text)
    CountyNumber (integer)
    AAA_ID (integer)
    MRA_ID (integer)
    LTSS Table
    County (text)
    CountyNumber (integer)
    City (text) -- optional used when there are multiple offices
    for a county
    IntakeNumber (text)
    Region (text)
    AAA Table
    AAA_ID (integer)
    AAAName (text)
    AAAPhone (text)
    MRA Table
    MRA_ID (integer)
    MRAName (text)
    MRAPhone
    MRAOffices
    MRA_ID (integer)
    IntakePhone (text)
    City (Text)
    CountyNumber (integer)
    My goal is for each county to list in a combined table:
    Column 1 = County Name
    Column 2 = LTSS Office (Number(s))
    Column 3 = MRA Intake Number
    Column 4 = AAA Intake Number(s)/City if not main
    Do I need a separate table for county that simply has the
    CountyNumber and
    CountyName to use as a control table?
    I'd like to do this as efficiently as possible -- thankfully
    the query won't
    be accessed by the general public and will be run only when
    updated
    information is received. Any suggestions as to order of the
    joins and
    groupings in CFOUTPUT? (what I have now creates a lot of
    duplication)
    Thanks in advance for your help,
    Michael Brown
    Webmaster, Texas Department of Aging and Disability Services

    Phil,
    Thanks for taking a look. You're definitely right. The data
    structures are a mess. What was originally intended to be on
    three
    separate pages has been requested to be "available at a
    glance."
    With both the LTSS Offices and MRAs having the possiblity of
    multiple offices for a given county what would be the best
    way to
    normalize the data? The tables for MRA, AAA, and LTSS have
    CountyNumber (county exists only in those tables to provide
    context for those who update the information manually (not my
    choice/decision)).
    So to break it down 254 Counties, each can have one or
    multiple
    LTSS numbers (and the number's city), only one AAA number,
    and one
    MRA with the possiblity for multiple intake numbers (and note
    containing location information).
    Hopefully, there is a graceful way of getting the output the
    way
    it has been requested. I'm open to suggestions.
    Thanks again,
    Michael
    "paross1" <[email protected]> wrote in
    news:[email protected]:
    > After taking a quick glance, it looks like you already
    have
    > normalization issues with your data model, since LTSS
    Table and
    > CountyCenter Table both contain County (text), and
    MRAOffices
    and LTSS
    > Table both have City (text), etc. It is hard to tell
    which
    fields are
    > primary keys and which are foreign keys to which tables.
    Some of
    these
    > that may have a one-to-many relationship that now
    changes to a
    > many-to-many will require a link table (associative
    entity) and
    the
    > foreign keys migrated to them.
    >
    > You need to resist creating actual "combined tables",
    spreadsheet
    > style, and
    > instead normalize your database, so that you can create
    your
    "combined
    > table" virtually using SQL. It is hard to offer
    specifics, since
    I
    > would need more information to do so, but the bottom
    line is
    that you
    > do have some obvious data model issues that need to be
    resolved
    before
    > you can get much further. Otherwise, you are going to
    have to
    write
    > some very kludgey SQL to solve your problem with your
    current
    model.
    >
    > Phil
    >
    >

  • Select with One-to-Many and Many-to-One without repeating

    Hi
    I have a customer who needs a report two sides left and right, but allowing for One-to-Many and Many-to-One relationships in the one report.
    A little background:-
    This has do do with listings on land and buildings.
    One building can be built on a few pieces of land.
    Similarly, there can be several buildings on one piece of land.
    What is required is a listing of buildings on the left, land on the right, but without repeating the "single line entries" either left or right.
    For example Building1 is on Land1 and Land2, and Building2 and Building3 are built on Land3.
    We need:-
    Building1 Land1
    ________Land2
    Building2 Land3
    Building3______
    The ___ just used for spacing so you get the idea ;)
    Essentially - a "break by" on columns on the left and right.
    The Buildings and Land are in different tables, with a link table - one row for each link.
    Any ideas?
    Thanks
    Mike

    To jitu.jk - first, this is not in SQL*Plus - its a report in APEX - second, I see no way to break on the left and the right in the same select.
    Maybe there is a way.
    To Etbin
    This is a very inovative solution - I've tried it out and the result is:-
    BUILDING LAND
    _____Land 4
    _____Land 3
    _____Land 5
    Building 2 Land 4
    Building 3 Land 1
    _____Land 4
    Building 4 Land 4
    Building 5 Land 3
    _____Land 4
    (The underscores I put in for spacing - not perfect but you get the idea - hard whe you write the reply in a fixed space font and it's displayed in the forum in variable space font!! ;)
    9 rows selected.
    This is not quite the desired result - in your list of associations, we have Building1 associated with Land 3,4, and 5.
    So for Building 1 we should have:-
    Building 1 Land 3
    ________Land 4
    ________Land 5..........
    But your result doesn't include Building 1 at all.
    The other requirement is that no building or land is ever repeated - so I came up with the concept of "groups".
    Starting with one building - I find all pieces of land that are associated - listing them on the right (without repeating the building.
    I then find any other buildings asociated with any of the land records that the first building was associated with.
    These are listed on the left - without repeating the land records on the right.
    This group is given a unique identifier of the minimum association ID (my associations have ID's).
    This all done, I use the unique ID as a break column ans summarise additional columns (area, value etc) below each group.
    Because of the summaries - adding area and value etc, I can't have any building or land duplicated as I would then "double count" the area, value etc.
    Maybe you method can be made to work with some tweaking.
    Very clever indeed - forums need great answers like this - it keeps us going.
    Thanks again
    Mike

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

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

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

  • ONE-to-MANY relationship between tables and forms in APEX

    I recently started using APEX and I have run into an issue.
    I have a ONE-TO-MANY relationship between two tables, A1 and A2, respectively.
    A1:
    A1_ID
    Item
    A2:
    A2_ID
    SubItem
    A1_ID
    I have 2 forms (lets call it F1 and F2) that I use to capture data for A1 and A2.
    On F2, I have the following fields that are setup to capture data:
         A2.A1_ID
    **A1.Item (this is a drop down that is populated using a SELECT statement where the select uses A1.Item field)
         A2.SubItem (user would enter SubItem)
    Note: A2.A2_ID is populated using a SEQ
    Everytime I pick **A1.Item on F2, is there a way to link to A1 table and display A1.A1_ID for every **A1.Item selected on F2?
    If so, I want to store the value captured in F2 for the A1_ID field into A2 table to maintain my 1-to-MANY relationship.
    If this will work, how do I go about implementing this solution?
    Can someone help me?

    I think it sounds like you are asking for a Master-Detail form. Try that and see what you get.
    chris.

  • How to resolve many-to-many join by 2 one-to-many joins

    Hi,
       I was asked many times how to resolve many to many relationship between two tables. I read to use 2 one -to- many relationships to resolve this. Can some expalin me when many to many relationship occurs between two tables and how to reslove them with practicle examples. Is there any article on this?
    Regards,
    Nanda Kishore

    Hi,
    Please check below link.
    http://www.forumtopics.com/busobj/viewtopic.php?p=859029&sid=20d79e3df07b0d8b41aadfbd902bb6b2
    http://blog.oaktonsoftware.com/2011/04/bridge-tables-and-many-to-many.html
    Thanks,
    Amit

  • Urgent : java bean having bidirectional one to many relationship

    Hi,
    We have complex requirement in our application.
    We need to copy java bean having bidirectional one to many relationship to another javabean having bidirectional one to many relationship..
    E.g
    Class Basket1 {
    public String color;
    pubic String type;
    public List<Basket1> basketList = new ArrayList()
    Class Basket2 {
    public String color;
    pubic String type;
    public List<Basket2> basketList = new ArrayList()
    We need to exact copy Basket1 to Basket2. We are in trouble to copy List of child because we do not have how many child Basket1 have of same type..
    Can someone help us how we can implement such kind of complex object bidirectional one to many relationship??

    I can't see anything bidirectional about these relationships. What I can see is a couple of BasketN classes that look identical so I don't know why they both exist, and they both contain lists of themselves as members, which suggests some kind of tree structure. Nothing bidirectional there. I can see tat these things can form circular object graphs but I don't see why you would want to do that.
    We need to exact copy Basket1 to Basket2And I don't know what that means. Please explain.

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

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

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

  • One to Many data model solutions

    Hello Friends,
    Recently I got a requirement where I need to  join two line item DSO based on a Reference key, but it is with One to many relationship. I hestitate to use the Infoset because its a very huge DSO, which will affect the report performance.
    I even thought of updating one DSO data to the infocube by getting the lookup values from other DSO in the transformation. I am stuck in every road I take to fulfill this requirement.
    Can anyone share your ideas and thought please...... It will really helpfull..... Thanks for your time.....

    Hello Ganesh,
    Thanks very much for your answer..... I will explain my issue below:
    DSO A: ( Delta load)
    Company_code     G/L_acct     Doc_number     Reference_Key     Invoiced Amount
    1000          1009673          767787          100008          100$
    DSO B: (Full Load monthly)
    Company_code     Reference_Key     Reference_Key_itm     Sold_to          Tax_paid_amt
    1000          100008          010               A          200$
    1000          100008          020               B          300$
    1000          100008          030               C          400$
    1000          100008          040               D          500$
    DSO C:
    Company_code     Reference_Key     Reference_Key_itm     Sold_to          Tax_paid_amt     G/L_acct Invoiced Amount
    1000          100008          010               A          200$          1009673          100$
    1000          100008          020               B          300$          1009673          100$
    1000          100008          030               C          400$          1009673          100$
    1000          100008          040               D          500$          1009673          100$
    If I load DSO B - - > DSO C , and the do look up on DSO A: Then I will miss the delta changes which happen in the DSO A
    Can I load both DSO A and DSO B to DSO C?
    Edited by: Ram on Nov 24, 2009 6:55 PM

  • One to many mapping

    Having trouble with the following poblem.. specially how to code getChildren??????? Help urgent
    Create a class called Families which creates a one-to-many mapping of parent name (String) to Child objects. Create any needed member variables and write the two specified methods. (You do not need to write the Child class.)
    class Families {
    public void addToFamily( String parent, Child child) {
    public List getChildren( String parent) {
    I have done the following..
    import java.util.ArrayList;
    import java.util.List;
    class Families {
    private String parentName;
    List <child> children = new ArrayList();
    public Families(String name){
    this.parentName = name;
    public void addToFamily( String parent, child kid) {
    Families f = new Families(parent);
         f.children.add(kid);      
    public List<child> getChildren( String parent) {
         return this.children;
    }

    Having trouble with the following poblem.. specially
    how to code getChildren??????? Help urgent
    Create a class called Families which creates a
    one-to-many mapping of parent name (String) to Child
    objects. Create any needed member variables and write
    the two specified methods. This key:
    (You do not need to write the Child class.)How can the following line possibly work?
    List <child> children = new ArrayList();It's not syntactically correct, AND you're not writing the Child class.
    %

Maybe you are looking for

  • HT1386 how to delete photos from iphone after syncing with itunes

    is there anyway to automatically setup itunes or my iphone to delete my photos from iphone after syncing with itunes?

  • How to get rid of 'BITMAP CONVERSION' in Execution Plan.

    Hi I am using oracle 10g. I am getting the path of execution of the query something as below. I have posted some part of it not all. I want to get rid of this 'BITMAP CONVERSION' Section of the path, is there any hint for the same in oracle? |  56 | 

  • MBPr 13 losing half charge overnight while asleep

    hello, i am new to Mac, have been using windows for over a decade now. so still learning ins and out of mac osx. but i have encountered something rather puzzling. randomly, my MBPr 13 would lose more than half its charge (yesterday night it went from

  • Animations Won't work

    I made a digital portfolio and it has external flash animations in it. When i view it on my computer (as either a .swf or a mac app) it works just fine. But when I put them on a CD (to give out my portfolio?) the animations will not work. Why is this

  • Is it possible to let Spry Tab Panels play and loop automatically?

    Hello everyone, I have created several Spry tab panels and they appeared to be working perfectly as I need them to. However, I was wondering if there is a way to have the tab panels play automatically and loop like a slide show on page load. So when