Howto get a random object from DB? - jpa

For more dynamism, I would like to add a random part on my app.
Here is what I would have done in other techs, and what is not working in play :
long id = JPA.execute("select id from Realisation r order by RANDOM() LIMIT 1");
And here is the stack :
unexpected token: LIMIT near line 1, column 55
Comments :
Either in app or database, makes no difference to me.
About hundred "realisations" in database.
All I need is there ID, no need for full object.
MySQL database behind it all.
EDIT
After a little investigation, here is how I've done it :
Define jpa.dialect in application.conf : jpa.dialect=org.hibernate.dialect.MySQLDialect
Fetch a complete object instead of just id with classic Model utilities :
Realisation r = Realisation.find("order by RAND()").first();

After a little investigation, here is how I've done it. Define jpa.dialect in application.conf :
jpa.dialect=org.hibernate.dialect.MySQLDialect
Fetch a complete object instead of just id with classic Model utilities :
Realisation r = Realisation.find("order by RAND()").first();
Not the best way possible, since I only need the ID and not the complete object. Anyway, I have no other solution. If anyone has one for just the ID I will take it.

There is no "limit" clause in JPQL, what you need is paging. You can use Query.setMaxResults instead if this is a JPQL query, which is not entirely clear in the post.

Related

Postgres: Update OR Delete exactly one row matching WHERE clause where many rows match

I have seen several solutions to this involving selecting with limit 1 and then updating using the primary key. This is the way I'm doing this now, but it is not efficient enough for my application.
Current query:
UPDATE "MappingTable" SET "DeviceId" = device_id WHERE "MappingId" = (SELECT "MappingId" FROM "MappingTable" WHERE "DeviceId" is null limit 1) AND "DeviceId" IS NULL RETURNING "Code"
Perhaps it is better to state the problem I am attempting to solve, because I am free to redesign the schema in order to solve the problem. The use case is: We have millions of devices that need to receive a one-time-use code from a table of possible codes. When we return a code, we set a column indicating which device is assigned that particular code. This needs to be as efficient as possible.
What we are doing at present is to have a mapping table with an int primary key, "MappingId", a "Code" column, and a "DeviceId" column. I am Currently testing with one million codes and 10 dummy "clients" banging on the service to test performance. I'm seeing very high amounts of locking and poor performance with a load of several hundred requests/sec, which is lower than what we expect in production.
I can design the database in any manner that will meet the requirement most efficiently. Again, I need to store a list of codes, then update/return exactly one code while recording the device that was assigned that code. I would appreciate any advice on design/query to meet that goal. I'm new to Postgres, so even having read dozens of questions/answers on SO and consulting docs for over a week, I am at a loss.
How are you determining which row to update/delete if your query returns many results? Can the solution be as simple as updating the row with where code = desired_code.

Sequelize how to use aggregate function on Postgres JSONB column

I have created one table with JSONB column as "data"
And the sample value of that column is
[{field_id:1, value:10},{field_id:2, value:"some string"}]
Now there are multiple rows like this..
What i want ?
I want to use aggregate function on "data" column such that, i should
get
Sum of all value where field_id = 1;
Avg of value where field_id = 1;
I have searched alot on google but not able to find a proper solution.
sometimes it says "Field doesn't exist" and some times it says "from clause missing"
I tried referring like data.value & also data -> value lastly data ->> value
But nothing is working.
Please let me know the solution if any one knows,
Thanks in advance.
Your attributes should be something like this, so you instruct it to run the function on a specific value:
attributes: [
[sequelize.fn('sum', sequelize.literal("data->>'value'")), 'json_sum'],
[sequelize.fn('avg', sequelize.literal("data->>'value'")), 'json_avg']
]
Then in WHERE, you reference field_id in a similar way, using literal():
where: sequelize.literal("data->>'field_id' = 1")
Your example also included a string for the value of "value" which of course won't work. But if the basic Sequelize setup works on a good set of data, you can enhance the WHERE clause to test for numeric "value" data, there are good examples here: Postgres query to check a string is a number
Hopefully this gets you close. In my experience with Sequelize + Postgres, it helps to run the program in such a way that you see what queries it creates, like in a terminal where the output is streaming. On the way to a working statement, you'll either create objects which Sequelize doesn't like, or Sequelize will create bad queries which Postgres doesn't like. If the query looks close, take it into pgAdmin for further work, then try to reproduce your adjustments in Sequelize. Good luck!

How to obtain the correct sequence number of class parameters in SQL?

Still on the task of reading class elements from SQL using JDBC... And I have a problem with class parameters.
Given those two SQL queries (both in namespace SAMPLES):
select name, sequenceNumber from %Dictionary.PropertyDefinition
where parent = 'Sample.Person';
select name, sequenceNumber
from %Dictionary.ParameterDefinition
where parent = 'Aviation.Cubes.Aircraft.StarAircraftModel';
the first query will correctly report the sequence number in the source file as it has been written.
However, this is not the case for the second query: sequenceNumber is always 0!
How do I obtain the "position" of a parameter?
Second query correct as well, but wrong target, because, such behavior possible for generated classes. You can see it by non-empty GeneratedBy property in definition for this class. If you try to do it for Sample.Person it will shown correctly.
But I still don't understand why you use JDBC, because it's so slow. I am not sure what are you doing, but maybe, my code can help you. Java class for reading Cache classes.

How I can do row locking in cakephp and postgres database?

I am using postgres database in my cakephp project.
I have a table with some data and a column called "status".
"Status" it's enum and can be "waiting", "in_progress", "completed".
My script has to get the first found record with status=waiting, change the status to "in_progress" and also get the id of this record and all this in one atomic procedure.
The id is needed after the computation to change status to "completed".
There will be many such scripts working in parrallel thats why I need this simple "row locking".
I am using postgres db for the first time - is there any easy way to accomplish this?
Maybe cake supports some convinient way of doing this?
with cakePHP it has no diffrence what kind of DB you have, simply use $this->Model->find... modify your status and then '$this->Model->save....`
$row = $this->Model->find('first',array('conditions' => array('Model.status' => 'waiting')));
$row['Model']['status'] = 'in progress';
$this->Model->save($row);
(...do something...)
$row['Model']['status'] = 'completed';
$this->Model->save($row);
propably you want to run it in loop and put some kind of const as statuses...

Get Objects from an ObjectSet by specifying a Range in EF

I am trying out EF 4.0.I have an Employee Object and using EF I am getting the Employee ObjectSet by simply calling
Context.Employees
Now the above call will spit following sql query
select * from Employees
The above query works fine and I don't have any complains on it however as you know this will not be performant enough if you have few millions of records in the table and it will definitely effect the performance.
So then I am trying to figure out a way to give a range to my ObjectSet where I can say something like get me records 30 to 60 from the Employee ObjectSet.
Is there a way to do something like this.
Any suggestions will be deeply appreciated.
Update:
I am trying to do this to get 20 Employees (page size) back based on the page index.
Thanks in advance.
NiK...
Ok, I finally figured out a way to do this which I think is pretty decent. And here is what I did.
I used the Skip and Take methods in IQueryable to skip and take objects based on the page index.
So I used the following code:
var empList = context.Employees.OrderBy("it.CreatedDate").Skip(pageIndex * 20 - 20).Take(20);
This is one way.
If anyone feel that this is not a good solution you are more than welcome to come up with something else which I can replace with.
Updated Code
As per Yury Tarabanko's suggestion I changed my code as follows:
var empList = context.Employees.OrderBy(x=>x.CreatedDate).Skip(pageIndex * 20 - 20).Take(20);
Thanks for those who took time to read my question.
Thnq,
NiK...