Question

I am reading data in gson from some web api. I want to insert rows in database in same order as they come in api result. Now when I am inserting data using ormlite with .callBatchTasks(new Callable<Void>() {} method, it inserts data in wrong order. In fact, it automatically inserts data by primary key. This means the data is ordered by primary key. In my model class I have used that column as id = true, nothing else. This is the same when I do not use CallBatchTasks function of dao.

Edited -----

But this is problem I have faced , what I had to do was I removed id = true from column and ran the same code then data was inserted in correct order that I wanted. Means data was Like
id value
2 data1
3 data2
1 data3
35 data4
23 data5

Now when I had id = true for column in this model class then data was inserted as follows when I inspected in database:-
id value
1 data3
2 data1
3 data2
23 data5
35 data4

but when I removed id = true from model class , then data was inserted in correct order as :-

id value
2 data1
3 data2
1 data3
35 data4
23 data5

I do not know where I was getting it all wrong in ormlite.First I had thought that it is problem while retrieving then I inspected the database and I was inserting data in wrong order.

Was it helpful?

Solution

it inserts data in wrong order -- in fact it automatically inserts data by primary key.

ORMLite imposes no order restrictions at all. If you call:

dao.insert(data1);
dao.insert(data2);
dao.insert(data3);

Then ORMLite will issue the SQL in that order. There is no queueing of data or commands at all.

I believe you are talking about how the data is retrieved from the database. Again, ORMLite imposes no order restrictions there as well. Database order is never guaranteed. After you call the above insert statements, you might page through the data and see it as data2, data3, data1. If you want a specific order then you should use the orderBy(...) query-builder method to specify it.

In any case, this is a database issue and not a problem with ORMLite. If you issue the same SQL queries via the database directly you will see the same output.

From your description, it looks like you are getting a different data order when you retrieve entities from the database that have a id = true. Again, the database can make the choice to iterate across the primary-key index if that is more efficient to do so. There is no restrictions on database order.

If you want the data in insert order then I would encourage you to add a generatedId = true and add an index onto the current id field. Then you can order by insert-order easily using the generated id field. However, this will mean that you will have to look up your current id field using dao.queryForEq(...) or something.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top