JavaDB - autoincrement among several tables - java

Is it possible to have autoincrementing id among several tables? What I mean exactly - I have (let's say five) tables, one of them is a table containing information about sales (sale_id, sold_item_id) and another four contain info about different kind of sold stuff. I want these four to share one pool of ids. How do I do that?
Edit.
I decided to choose Juxhin solution and I created additional table. Everytime I create a record in one of these 4 tables, I autoincrement new id in that additional table and this id is in one of columns of that new row.

This sounds like the use case for a sequence and the link seems to indicate that javadb supports this.
So you create one common sequence for all tables:
CREATE SEQUENCE MASEQUENCE
and then use it when inserting into your tables:
INSERT INTO TAB1(ID,....) VALUES(NEXT VALUE FOR MYSEQUENCE,...)
Each NEXT VALUE will advance the sequence and so all ids will be unique across all tables.

If you want a new record to be inserted into all 5 tables when you insert something into one of them, then you can create a trigger for this.
It may also be helpful to create foreign keys on the id columns in the other tables (to keep the tables in sync).

Related

JPA Single foreign Key ID to refer to two (or more) tables

Simple question really. This is using JPA on Java and what I what to do is to have a table with and column which can refer to one of two tables. To make this clearer I can have a 'User' table and a 'TempPerson' table. I don't want to pollute my User table (as I use it for security as well, plus has other info as well). Now lets say I have a third table called 'Game'. Now when someone stars a game against someone, they can play against someone in the system already ie. User or someone where they can type a name and new entry for TempPerson is created and used. So the game for player2 (or player1) will be a mapped id to either User.id or TempPerson.id. Now I understand that a determining column may need to be placed into Game to determine what the Id is for but I hope JPA will cater for it somehow. Any ideas will be helpful, i could use inheritance but not sure about it.
Here is another example:
Lets say I have a table which holds information about images => id, resolution, width, height, location, bucket .... id_in_the_table_where_used, table_name_of_where_used. Now, this one table can hold the images for profiles, places, etc... and the profiles, places will have an id referring to the images table, but I also would like the images table to have an id back to where the images is used, which table and which id is using it.
It almost I am asked i 'one to many tables' solution. Although I could have many in between tables etc... Seems overkill to so something quite simple, although many DBAs may be cursing this idea. It does minimise queries, number of tables etc...
Thanks in advance
It is possible to use single FK to target multiple tables. You would have to use #JoinColumn for that
#Entity
public class User{
#OneToOne
#JoinColumn("universalId", targetEntity=Avatar.class)
private Avatar
#oneToMany
#JoinColumn("universalId", targetEntity=Log.class)
private List<Log> logs;
}
This would use universalId column of User's table to lookup related records from Avatar and Log tables
This however is rather anti-pattern, causing a lot of consequences when for example universalId will have to be changed etc. 1 column = 1 FK - go that way.

Hibernate query to fetch records taking much time

I am trying to retrieve a set of records from a table. The query I am using is:
select * from EmployeeUpdates eu where eu.updateid>0 and eu.department = 'EEE'
The table EmployeeUpdates has around 20 million records. 'updateid' is the primary key and there are no records currently in the table with the department 'EEE'. But the query is taking lots of time, due to which the web-service call is getting timed out.
Currently we have index only on the column 'updateid'. 'department' is a new column added for which we are expecting 'EEE' records.
What changes can I make to retrieve the results faster?
First off, your sql isn't valid, looks like you're missing an 'and' between the 2 conditions.
I'm guessing that all the update ID's are positive, and as its the primary key, they're unique, so I suspect eu.updateid>0 matches every row. This means it's not technically a Tablespace scan, but an index based scan, although if that scan then has all 20 million rows after matching the index, you might as well have a table space scan. The only thing you can really do is add an index to the department field. Depending on what this data is, you could have it on a seperate table, with a numeric primary key and then store that as a foreign key on the eu table. This would mean you scanned through all the departments, then got the updated associated to them, rather than searching every single update for a specific department.
I think you should look into using a Table-per-subclass mapping (more here: http://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/inheritance.html#inheritance-tablepersubclass-discriminator). You can make the department the discriminator and then you'd have a EEEEmployeUpdates and ECEmployeeUpdates classes. Your query could change then to just query the EEEEmployeeUpdates.

SQL inserting data into two different tables

I'm reading user data from a Java GUI and trying to record it into two different database tables with a single statement. I'm fond of the 'insert into' statement, I just dont know how to enter data into two different tables (which are linked with a foreign key in the one of them), using inner joins and stuff..
Please, any help is welcome.
So far I've had all columns I need in one table but after normalising the database to 3NF I'm not sure of how to insert into all of them..
You need to use two insert statements. In the first statement you have insert data in the primary table and in the second statement you have to insert on secondary table ( where first table reference id will be used)
If you do opposite there will be constraint violation error from database.

How to resolve data confliction

I have several databases ,and need exchange data between them. When I export from db A import into db B, Id confliction will happen. I think out two approach, no one satisfy me.
select max(id) then create new id to avoid confliction ,but one column store json structure and contains id too! (history reason). So I need create new Id (primary key) and modify all ids in that json column.
or I can add a batch info for each data import. When I import data, I find out every id in sql and add batch id before them. Such as:
The original db like:
ID COL_JSON
11 {id:11,name:xx ...}
I want to insert a new record :11 ,after insert I add a batch info "1000" before id
now db looks like
ID COL_JSON
11 {id:11,name:xx ...}
100011 {id:100011,name:xx ...}
the next batch will be 1001,1002 1003 ..., so if a new 11 record need to be insert the db looks like
ID COL_JSON
11 {id:11,name:xx ...}
100011 {id:100011,name:xx ...}
100111 {id:100111,name:xx ...}
Although the two approach can resolve conflict, I feel the two approach is stupid. Is there some graceful scheme?
For legacy system, there is no better approach except to align with it. We cannot change it more on legacy system, so your 2th approach seems good. Frankly, tt's not stupid and just the right way to go.
I don't understand exactly what your databases exchange.
If you need data from both databases in both of them you could use something similar to your batch but using characters - A11 and B11 ids.
This way you won't have conflicts even if your database grows a lot.
Edit: You could make also a primary key with two fields: the integer ID with autoincrement and a varchar for the original database name.
When I have a table that should be synchronized (not on the fly), I use this approach :
The main table that will be overwritten has a big autoincrement (ie : autoincrement = 100000)
The secondary table that will be merged to the main one has a normal autoincrement starting to 1.
The only requirement is that you ensure that the main table has a big enough autocrement set up, so the secondary table id will never reach the main table first ID

Generate xml dynamically in java using data from a table in database

Here is the problem that i am currently stuck with for the past few days. And I am looking for guidance / approaches on how to handle.Hints & suggestions welcome.
so here is the problem.The database has a table "group" which has two columns : group_id on parent_group_id.group_id is the primary key for the table .All entries in this table represent groups/sub-groups.If one adds a sub-group from the front end ,then an entry gets inserted in to the group table with an auto-generated group_id which MySQL generates.the parent_group_id corresponds to the group_id of the group on which a sub-group was added.So in essence it's acting like a foreign key to the group_id column.My task cut out here is to generate an XML in java using the data from the group table. So this is where i am stuck.I know it's gonna be a recursive function which needs to be written but cant figure out a way how to dynamically create the nodes and fill the data from the Db at the same time.The end XML needs to be sent as json data to the front end.
A group can have n-sub groups and the hierarchy can go on.For ex- Say Vehicle is root node with group_id =1.It can have cars & bikes as sub-groups.so the parent_group_id will be 1 for car and bike and group id say will be 2& 3 respectively.
P.S: this is the first time i am posting here having had used this site for the past one year.Please let me know if any more info is needed or whether you are able to comprehend my problem.
If you split the task into two, it will be more manageable.
Here are some useful links on querying hierarchical data in relational databases and specifically in MySQL:
What are the options for storing hierarchical data in a relational database?
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
http://www.slideshare.net/billkarwin/models-for-hierarchical-data
http://en.wikipedia.org/wiki/Common_table_expressions#Common_table_expression
As long as you have the query result properly sorted, you will be able to traverse it recursively, building the XML tree step by step.
Was able to solve it by using recursive functions :). Loaded all the data using the entity class and then iterated over the data using recursive functions to build the tree like structure.I didn't try and take the sql way.

Categories