Persisting an instance of the many side of a in one to many relationship

It seems as if most books only tell you how to setup the relationship for a one to many relationship but seems to fail to tell you the appropriate way to persist in this relationship. So, I have a parent class with many child classes. Also, I am using services and so I am converting from Entities to Dtos and visa versa.
First, i want to insert a new child for the parent. Do I just convert the child Dto to a child entity and then persist the child entity with the reference to the parent? Then do I find the parent and add the child to the parents children so the entities are consistent?
Or do I do a find on the parent and add the child to the parents children list and the child. Will the child be persisted automatically?
With this said, what about updating a child? Do I remove the existing child and add a new one? or do I somehow find the child in the parents children set and update the info there and then somehow the child is persisted automatically? And since I am using Dto to entity, do I use a find to find the parent and then iterate through that parents children til I reach the child I modified by id somehow.
What about Many to Many relationships? With a middle join table? How does JPA know to remove a join if I change the child reference? Does it remove the old and insert the new? Or do I have to do it myself somehow. Which if the later then I really can not have a parent child Dto I really need a parent childlink table where the child is referenced by the linktable? The book I have been reading has not made this very clear.

Hello,
The relationships cascade settings determine what should happen. I would not recommend persisting a new entity that references a non-managed entity. Instead either persist the child then make the associations or find the parent, make the associations then persist the child. In the second case, you do not need to explicietly persist the child if the parent->child relationship is marked cascade persist, since it will be found on flush or commit.
Since you are using DTOs, updates require you merge the changes. You can directly merge the child, and if it has a link to its parent, modify the parent to add the child on the managed child that gets returned.
As for ManyToMany, you must modify the side that controls the relationship. So if the parent owns it, then you must modify or merge the changes into the parent for the changes to be persisted to the database. If it is bi-directional, you must modify both sides so that the cache remains consistent with the database. This should be transparent to your application, and you only need an entity for the relation table if you want to map more complex information that doesn't fit into the JPA ManyToMany options. Otherwise, JPA should handle inserting and deleting enteries to the relation table for you.
Best Regards,
Chris

Similar Messages

  • SQL requests when handling a refresh on a persistent-dirty instance

    I just noticed that Kodo issues two SQL requests when handling a refresh
    on a persistent-dirty instance, the first one getting the JDOLOCKX
    column value.
    For a persistent-clean instance, it makes sense to get the version
    number first and to check if it has been changed. If not, the attribute
    values are not read from the database.
    For a persistent-dirty instance, as the memory state has been changed,
    it has to be reloaded anyway and it seems to me that the first request
    is useless.
    Any confirmation ?
    Thanks.

    Yeah, the version check seems to be extraneous. We'll see what we can do
    about that. Thanks for pointing it out!

  • Persistence and transactions: One-to-many consistency problem

    Hi,
    we have the following problem: We have two persistent classes A and B that are connected via a one-to-many (1:n) relationship. Now we
    1. get an object "a" of class A and a number of related objects of class B from the persistence manager. Then we
    3. delete the relationship between "a" and one object of class B. Then (without commit)
    4. the GUI requests to show all related Bs for our given "a" and:
    5. the query returns also the "deleted" object.
    All these steps are performed within the same (object oriented) top level transaction.
    The reason for this seems clear to us: The removal of the B has not been persisted in the DB. However, we don't really know how to deal with it...
    Any suggestion is welcome.
    Christoph

    Hi Chris,
    it is unclear to me if you are re-reading the database after you delete the 'b' item.
    Anyway, the way persistent objects work is that changes are not written to the database until the SAP LUW ends with a COMMIT WORK.
    Cheers
    Graham Robbo

  • Toplink mapping for one-to-many object inheritance

    Hi
    I currently have a Person object, extended by two specialist classes, PremisesLicenceHolder and PersonalLicenceHolder. I have mapped this in Toplink and it works fine saving a person into the specialist tables using the primary key person_id.
    However, a single Person may be extended any number of times by either one or both of the two specialist types. So, a Person may be a PremisesLicenceHolder many times over for different premises and licences, and also a PersonalLicenceHolder several times over.
    Is it possible to map this object model in Toplink avoiding duplicate person_id primary keys in the specialist tables?
    Thanks

    Hi,
    I am happy that my object model fits the problem domain. The Person and Organisation objects contain base information and have the primary keys person_id and organisation_id. It is important that there is no duplication of person and organisation records, no matter how many times they are saved in different roles.
    There are two types of licenceholder in the problem domain, and the ILicenceHolder interface defines information and methods that are common to both. The PersonalLicenceHolder object represents one of these types of licenceholder, and is always a person, so this class extends Person and implements ILicenceHolder.
    The additional information and methods that are required by the second type of licenceholder are defined in the interface IPremisesLicenceHolder, which extends ILicenceHolder. Premises licence holders can either be people or organisations, so I have two objects to represent these - PremisesLicenceHolderPerson which implements IPremisesLicenceHolder and extends Person, and PremisesLicenceHolderOrganisation which implements IPremisesLicenceHolder and extends Organisation.
    The model is further complicated by the fact that any single Person may be both a PersonalLicenceHolder and a PremisesLicenceHolderPerson, and may be so several times over. In this case, the same basic Person information needs to be linked to several different sets of licenceholder information. In the same way, any single Organisation may be a PremisesLicenceHolderOrganisation several times over.
    Sorry this is complicated!
    My initial idea for the schemas is to have Person and Organisation tables containing the basic information with the primary keys person_id and organisation_id. The Person table would have a one-to-many relationship with both the PersonalLicenceHolder table (pk: personalLicenceHolder_id, fk: person_id), and the PremisesLicenceHolderPerson table (pk: premisesLicenceHolderPerson_id, fk: person_id). There would also be a one-to-many relationship between the Organisation table and the PremisesLicenceHolderOrganisation table (pk: premisesLicenceHolderOrganisation_id, fk: organisation_id).
    I am flexible as to the design of my schema though, as I am happy to adopt any that will facilitate the Toplink Mapping.
    Thanks for your help with this.

  • On WLC 'one-to-many' means one VLAN mapped to multiple SSIDs possible?

    Does the Cisco Wireless LAN Controller Architecture includes this feature (configuration possibility)?

    Thanks all for the provided infos. We have now the same requirements for two customers -> One-to-Many (One VLAN mapped to multiple SSIDs).
    Can anybody who has realised such a set up provide some more details how to proceed?
    The link from David describes the other way around, several VLANs mapped to one SSID. By the way, we where able to implement this, but it is only supported in centralized mode, local mode (Flex Connect it doesn't work).
    For any advise how to proceed for "One VLAN mapped to multiple SSIDs" would be very appreciated.
    Thanks Erich

  • One to many shuffle

    Hi Guys
    I want to know how do we save the data from one table to another as soon as the user shuffle the things in one to many shuffle
    this one to many shuffle is done based on selection of Radio group
    When user select a radio button as per that the data will be displayed in one to many shuffle below
    what I want is When the user shuffle the things which he wants then it should immediately go and save in another table based on primary keys
    How can I do that???
    Any suggestion is Appreciated
    Thanks ,
    Santosh.

    You can have af:switcher component to display ADF Form and ADF table and based on your value of Radio button hide/show the facet
    check this little example http://www.youtube.com/watch?v=tMuZJvU5eTk&feature=plcp

  • One to Many Mapping Expression

    I have two tables. Invoice & Accounts
    An Invoice can have many Accounts associated to it(one to many)
    i need to select all the invoices whose accounts belongs to a particular category and region
    Invoice has
    invoiceNo
    Accounts has
    AccountID
    AccountRegion
    AccountCategory
    InvoiceNo
    i made a expression like
    ExpressionBuilder builder = new ExpressionBuilder();
    Expression exp1 = builder.anyOf("accCollection").get("accountRegion").equals("1");
    Expression exp2 = builder.anyOf("accCollection").get("accountCategory").equals("VIP");
    Expression exp3 = exp1.and(exp2);
    ReadAllQuery query = new ReadAllQuery(Invoice.class,exp3);
    query.setPartialAttribute("invoiceNo");
    query.dontMaintianCache();
    uow.executeQuery(query);
    The result is coming properly, but when i looked at the query, it is joining the Accounts table two times. when i increase the number of expression based on the Accounts table then it is joined as many times as there are in my query
    e.g.
    select t0.invoiceNo from Invoice to,Accounts t1,Accounts t2 ...
    How can i make the query so that the Accounts table will be used in the join only once??
    Sathish

    Do this, and all will be well:
    ExpressionBuilder builder = new ExpressionBuilder();
    Expression exp = builder.anyOf("accCollection");
    Expression exp1 = exp.get("accountRegion").equals("1");
    Expression exp2 = exp.get("accountCategory").equals("VIP");
    Expression exp3 = exp1.and(exp2);
    Think of it as building a tree and the SQL will build down the branches.
    - Don

  • One-to-many in bubble chart - or a 'stacked' bubble chart?

    Hi all
    I am working on a bubble chart app. I have found many examples of using the bubble chart to display data in a one to one basis - so there is a single data point which has a value one both the horizontal and vertical axises.
    Can someone please tell me how I can have display data which has a single vertical value, but multiple datapoints on the horizontal - and all data points for that single vertical value are dislayed on the same line?
    I hope I have explained this clearly.
    In a bar chart this is called 'Stacked'. Can I do a similar thing with a Bubble Chart - is it even possible?
    Kind regards,

    OK I think I can answer my own question.
    it seems that the Bubble Chart can have a one-to many data points. the problem was that the horizontal and vertical axis would display duplicate values.
    I found this link to be useful: http://www.mail-archive.com/[email protected]/msg96652.html//www.mail-archive.com/[email protected]/msg96652.html

  • Simple one to many mapping question

    Hi,
    In the Toplink tutorial there is a one to many relation between Employee and PhoneNumber, and one to one between PhoneNumber and Employee.
    If I don't require can I eliminate the one to one relationship between PhoneNumber and Employee. Or Toplink requires it?
    Thanks
    -Mani

    Hi,
    The purpose of creating one-to-one back reference mapping in the target is so that the foreign key information can be written when the target object is saved. Alternatives to the one-to-one mapping back reference include:
    Use a direct-to-field mapping to map the foreign key and maintain its value in the application. Here the object model does not require a back reference, but the data model still requires a foreign key in the target table.
    Use a many-to-many mapping to implement a logical one-to-many. This has the advantage of not requiring a back reference in the object model and not requiring a foreign key in the data model. In this model the many-to-many relation table stores the collection. It is possible to put a constraint on the join table to enforce that the relation is a logical one-to-many relationship.
    Raanan.

  • Create One-to-Many Work Item Links Programmatically in TFS 2013

    Hello,
    I urgently require some help with this problem please.
    I have a number of existing work item types - for illustration purposes, let's call them Work Item Parents and Work Item Children. Remaining details are as follows:
    I have thousands of Work Items of type Parents
    I have hundreds of Work Items of type Children
    The Work Item Parents have a One to Many relationship with the Work Item Children
    Both Work Item types have already been added to TFS and we now need to associate or link Parent items with their corresponding Child items.
    Due to the sheer number of items described above, linking the  Parent items with their respective Child items would be a complete "No-No" as it could take forever to complete and would be prone to error.
    What I'm therefore seeking is the ability to programmatically associate or link the two work item types where required.
    Any advice on how to achieve this would therefore be greatly appreciated.
    Thank you.
    PS: The link type between my work item types do not necessarily have to be of a Parent-Child relationship. "Related" work items will do just fine.

    Hi RegManteaw,  
    Thanks for your reply.
    We can get the wanted Bug work items and Task work items using
    WorkItemCollection, you should use the logic code to handle which Task work items linked to which Bug work item. For example, I defined 5 Bug work items within “b1” tag, and 10 Task work items within “t1” in my test
    team project, then I run the below code snippet to get that Bug/Task work items and link 2 Task work items to one Bug work item.
    TfsTeamProjectCollection tfs =
    new
    TfsTeamProjectCollection(new
    Uri("collectionURL"));
    tfs.EnsureAuthenticated();
    WorkItemStore workitemstore = tfs.GetService<WorkItemStore>();
    try
    // get “b1” bug work items(5) from test team project
    string wiql =
    "SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = 'teamprojectname' 
    AND  [System.WorkItemType] = 'Bug'  AND 
    [System.Tags] CONTAINS 'b1'";
    WorkItemCollection Bwic = workitemstore.Query(wiql);
    // get “t1” task work items(10) from test team project
    string wiql2 =
    "SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = 'teamprojectname' 
    AND  [System.WorkItemType] = 'Task' AND 
    [System.Tags] CONTAINS 't1'";
    WorkItemCollection Twic = workitemstore.Query(wiql2);
    //two task work items linked to one bug work item
    for(int
    i =0;i<=4;i++)
    //define the link type
    WorkItemLinkTypeEnd linkTypeEnd = workitemstore.WorkItemLinkTypes.LinkTypeEnds["Related"];
    //link first task to bug
    Bwic[i].Links.Add(new
    RelatedLink(linkTypeEnd, Twic[(i * 2)].Id));
             Bwic[i].Save();
    //link second task to bug
    Bwic[i].Links.Add(new
    RelatedLink(linkTypeEnd, Twic[(i * 2 + 1)].Id));
    Bwic[i].Save();
    catch(Exception
    e)
    Console.WriteLine(e.Message);
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • �possible that the JNI side generates many instances of the native code?

    Hi guys,
    I asked this in a previous post but maybe with a bad constructed question.
    I have C code that generate data (particles) for one client (non multithreading). In my webapp Im gonna have many clients but changing the C side is not initially my best solution.
    When one client connects to the server ( calls the C code to generate data) it works ok, because I have only one client. When two or more clients connects to the server,
    the data generated by the C side is DIVIDED over all clients. So, I need 'n' replications of the C side, non one C side, this way my data structures in the C side will be replicated
    'n' times and could generate data for 'n' clients. Hope I have explained the right way.
    Please replies! :).

    1. Serialize the requests into the C code so that only one request is active. Save any state elsewhere. (Could be saved in java, could be saved in some C-side structure)Hi bschauwejava,
    I think my problem is not concurrency, saving the state in java will mean a lot of overload but its an option.
    Do you mean there is no way of having many instances of the C code ? this way I will have my state in each particular instance (one instance per client connected), and I could can forget about state.

  • Which SQL Server Edition support how many sessions to the instance from SQL Management Studio on the client side

    Hi,
    I'm looking for some help on the below query to verify which version of sql server edition supports multiple or N number of sessions to the SQL server Instance using the SQL Server Management Studio tool from the client side.
    SQL Standard Vs Enterprise.
    your urgent help is much appreciated.
    Br.

    Hello,
    See Maximum Capacity Specifications for SQL Server =>
    User connections = 32,767; and this value is independent of use SQL Server Version, edition or the used tools, like SSMS in your question 
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • [database design]  the "too many" number of users of one instance!!

    Good morning everyone!!
    I have a question about the number of users of one db
    instance, "possible problems" caused by too many users,
    and "pros and cons" of this case.
    Now, the company I work for is considering centralizing
    150 db servers of 150 sites. 150 chained-stores have
    their own db instance.
    Here is the structure of db instance after the
    centralization.
    1. Centralized instance has each user per site(150
    sites), for example, site001, site002, …site00n, …
    site150
    2. Each user has its own 250 tables, thus the db
    instance become to have 150 users and 150*250 tables.
    3. Each user has almost the same table schema, not
    exactly. There are a little bit of differences among
    the business rules of each sites.
    4. the version of centralized db instance is "oracle9i".
    Theoretically, it seems like there is no problem, but I
    have not experienced the db instance like this, which
    has "too many" users of 150 users.
    In terms of every aspect such as "performance/tuning",
    "system management", or "something else", I would like
    to hear what could be "the pros and cons" of this
    structure.
    Assuming that there are possible critical problems caused
    by too many users, what could be the alternative choice?
    I will be waiting to hear your experience. Every response
    will be appreciated, even if it is not about what I asked.
    Thanks for your interest in advance.
    Have a nice day.
    Ho from Japan

    Have a look to following AskTom threads:
    http://asktom.oracle.com/pls/ask/f?p=4950:8:4685256847630125933::NO::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:31263903816550
    http://asktom.oracle.com/pls/ask/f?p=4950:8:4685256847630125933::NO::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:63447102315094

  • SSRS 2008 - How to filter records from the many side base an specific criteria

    I have a report that displays a summary of all the actions taken for specific project, I need to restrict those records based one of those options from the left side table.  If case 1 was
    denied it should not show in the report.  I need help with this query
    Please Help me  Angie
    Ex:
    Project name
    Actions
    Case 1
    Received
    Process
    Sent for Modifications
    Received w/Modifications
    Denied
    Case 2
    Received
    Process
    Sent for Modifications
    Received w/Modifications
    APPROVED
    Case 3
    Received
    Process
    Sent for Modifications
    Received w/Modifications
    Inactive
    Project name
    Actions
    Case 1
    Received
    Angie

    Hi,
    You can set the Rowvisibility  of the detail row to hide based on the expression
    =IIF(Fields!Actions.Value="Denied",True,False)
    Many Thanks
    Chandra
    If this Answers your issue please mark as answered.

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

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

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

Maybe you are looking for

  • New Problem...installing Ovi maps

    cant install even update in facebook,internet radio... i got the latest nokia suite... Solved! Go to Solution.

  • Query on view - IS the querry executed each time view is referred?

    I want to know whether query inside a view is executed each time when the view is being referred? Also which on of below will be faster? select      a1.x,      a1.y,      b1.z from      TableA a1,      TableB b1 where      a1.keyName = 'F' || b1.some

  • Merge LiveCycle Form with XML using JAVA

    Hello. I am trying to find out how to merge non-interactive form with XML (using JAVA) so the users can see the final output form with the data filled in. What are my choices..? So far, I have created the interactive forms as template using LiveCycle

  • Texture Rendering quality

    Hello everyone, I'm creating a simple J3D program that contains a flat plane with a texture applied to it. I'm finding that the rendering quality of the flat plane is unacceptable though. The image is very blurred, as though it has been dithered thro

  • How to transfer iPhoto library into another existing iPhoto library?

    Hi. I need to transfer iPhoto (the whole library - created folders and the events the way they been downloaded from camera) from Imac iPphoto to an existing MacBook iPhoto library. I did find in here how to transfer the entire library to the new comp