In my application I have a component that receive objects from another components and insert them to MySQL DB. Currently I’m buffering the objects and once in a while (few seconds) the objects are inserted to the DB using a batch (using JDBC, not hibernate).
I would like to break this objects to 2 objects, then two buffers, and finally insert them to 2 different tables.
My first thought was to use MySQL auto generated ID to tie the two sub-objects together in the table (as foreign key).
My problem is – how will I know the auto-generated ID for the ‘father’ object when I insert the ‘child’ object?
My ideas are:
- Generate my own ID before splitting the object and send the ID to the DB myself, without using MySQL auto-generated ID.
- Use stored procedure that will insert the first object, use MySQL’s
LAST_INSERT_ID();
What do you think?
Your essential problem is that you need information from the database for one object before you can store the other object.
Let’s say you split your compound object into two smaller objects, namely Place and Map.
If you must have two buffers to store Place and Map, then I see three ways of doing so:
Put only Place in the store-buffer. When Place is stored, and the PK has been read from the database, ONLY THEN place Map in the other store-buffer.
Put Place and Map in their own store-buffers. When a Map is about to be stored, check it’s associated Place, to see if the PK has been generated yet. If it has, then store the Map. If it hasn’t, then skip that Map and check the next Map.
Put Place in the store-buffer. When it gets stored, read the PK, and immediately store the Map also. This obviously does not use two store-buffers.
Look at how other objects are stored in your application. Certainly they don’t generate their own IDs before they are stored in the database. Certainly you don’t try to put them in a store-buffer before you have all the information necessary to store them. My recommended course of action is therefore option 1 or 3.