How to add 1 on the "like" value using QueryDSL - java

In my postgres db, I have a cell to save how many people clicked "i like" for the corresponding post. However, I am wondering if my current solution is concurrent in postgres. What I did now is two steps in my dao class.
1) fetch the current value in DB.
2) add 1 and then update it.
If no, how can I make it concurrent? I am using Java (querydsl) and Postgres. Can any one help, please?
Update:
Thanks for the answers. One thing I didn't make clear is that I use querydsl. So I don't use normal column way. But still thanks.

Assuming your table is named posts and you have a QPosts query class, then you can do:
QPosts p = QPosts.posts;
queryFactory.
update(q).
set(q.likes, q.likes.add(1)).
where(q.id.eq(42));
This would then generate the following SQL:
update posts
set likes = likes + 1
where posts.id = 42

I've never do PostgreSQL but I found something.
UPDATE tableName
SET likes = likes + 1;
Tell me if it's good,
Happy if I help you !

Related

Auto Create MySQL Tables on First Run Java/MySQL

I am trying to Auto create SQL tables on first run, and haven't found any good tutorial on google. Does anyone have a suggestion or can explain it to me. My class so far looks like: http://pastebin.com/6u8yFWrt
In Mysql you can do:
CREATE TABLE tablename IF NOT EXISTS...
This will, as the name says, create the table if there is no table with the same name, described here. If you run it whenever you open the connection to the database, you should be fine.
BUT this is no guarantee that the existing table has the format you want! If you change the definition of the table halfway through the process, because you want an extra column, you will need to delete the existing table fist, for the changes in the query to have an effect.
I think you should use JPA and Hibernate instead. Youre probably in for quite a journey until you get the hold of it but I think it is worth the effort.

SQL insert or update through servlet

I am learning Java and have big problem with SQL query. I have field that should be updated if exist or inserted if not exist.
Firstly I tried with IF NOT EXISTS, but it turns out that Oracle doesn't support that.
Then I tried with EXCEPTION WHEN NO_DATA_FOUND, but it also failed.
After few hours of searching I found out that MERGE must work on my example, but for some reason I couldn't make it to work. I have never used merge before, so maybe I made mistake in query, but I don’t think that’s the problem.
So, I have table commercial and field in it idArt, idPla, quan and ID (unique and auto increment). From html form I am sending first three values to servlet and then servlet should do next thing:
if there is row with idArt=(formIdArt) AND idPla=(formIdPla) then update quan=quan+(formQuan), ELSE insert all three values.
This looks simple, but I have already lost way too much time on this, so can please someone help me with this?
First,
Try to update your table like this:
update commercial set quan = quan + formquan where idArt=formIdArt and idPla = formIdPla
if execution of this query returns result as more than 0 row affected then do not insert all three values, else insert all three values in your table

How do I update a certain field of a Model in Playframework?

Suppose we have a User class, if I want to update it's name:
User user = User.findById(123);
user.name = "someone";
user.save();
The generated SQL would be
update user as user0 set user0.name = ? user0.email = ? .....
That means Play didn't realize I just want to update a single field. Is there any way could make the generated SQL only update the specified fields ?
Info: this is answer for Play 2 + Ebean! so it DOES NOT work with Play 1 + JPA
There are some options in Ebean's API, so you should check it and choose one:
Update<T> - check in the sample for #NamedUpdates annotation
Ebean.createUpdate(beanType, updStatement)
SqlUpdate - you can just perform raw SQL update, without need for giving the entity type
This is dependent on whether Play (or actually Avaje Ebean) actually tracks which of the fields are changed. It's simpler to update all of the fields instead.
This isn't an issue performance-wise either, so I wouldn't waste too much time looking for a solution.
You can use hibernate's dynamic update feature : http://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/
But remember that this have negative impact on performance as database cannot cache statements. See here for others explanations : Hibernate : dynamic-update dynamic-insert - Performance Effects

How expensive would a DELETE and INSERT be relative to multiple SELECTs and an UPDATE?

My question is a little vague at the moment since I'm not sure that I'm supposed to post any company code online or anything. But here goes.
Suppose I need to update a specific field in a MySQL database. In order to do this using my Java client program, I have to use multiple SELECT statements in order to check that the field should be updated, and then appropriately update it using the information that has been retrieved.
eg.
//created a Connection called con already...
PreparedStatement selectStatement = con.prepareStatement("SELECT * FROM myTable" /*+ etc*/); //example query only! I'm not actually going to use "SELECT * FROM myTable"!
//more selectStatements follow
PreparedStatement updateStatement = con.prepareStatement("UPDATE myTable SET field1 = ? WHERE id = ?");
ResultSet rs = selectStatement.executeQuery();
//more ResultSets from the other selectStatements
//process ResultSets and retrieve information that indicates wwhether an update must take place
if(conditionOccurred) { //Assuming we need to update
updateStatement.setText(...);
updateStatement.executeUpdate();
}
(I haven't included try-catches in the code (sorry, I'm a bit lazy since this is just a contrived example) but I'd have to catch the potential SQLExceptions as well, I guess...)
What I'm wondering is: will it still be more "expensive", or costly in terms of speed if I delete the row and then insert a new row that contains all the updated information, given that I now need to use multiple select statements to check whether an update should occur? (memory is not such a big issue at the moment, though if something I've done has a massive flaw with regards to this I'd love to hear it!)
TL; DR: If I use multiple SELECT statements and then an UPDATE to some field(s), will it be more efficient to simply DELETE and then INSERT a new row?
Extra details: the table I'm working with at the moment has an auto-incremented ID, a VARCHAR field (the one to be updated, has a uniqueness constraint), 2 date fields and a CHAR(64) field. Not sure if it helps in answering the question, but I'll provide it anyway.
Please let me know if there are more details you'd need, and thank you in advance to anyone who might provide some insight.
To fully answer your question we would need to see your SELECT statement, however if your UPDATE does not alter the primary key values I would assume UPDATE is more efficient. The reasoning behind this is that an index values would not have to be adjusted where in the case of the DELETE & INSERT the index would be.
As in most cases the only sure fire way to test this is by using both methods and bench marking the elapsed time.
I'm answering your question based on the knowledge I acquired from my advanced database management course. I would say it would be very subjective as your concern is in terms of speed here and not the usage of memory.
When retrieval are done, in terms of your Select statements, your data are cached and when any necessary Update are required, you directly edit the fields in the cache. This save a read and write trip if you were performing the latter of Delete and Insert.
This would in my understanding, save you processing time in terms of millisecond for one single transaction, and if you look at a big picture, it will save you a lot when multiple transaction are performed. However, if your select statements involves too many queries dealing with a large size of data, it might turn out that your latter method is more efficient.
I believe with your additional inputs of your SQL statements, we would be able to give you a better and more accurate advise. :) I hope it helps.

Java JDBC UPDATE Add Number?

So let's say I have an int column in MySQL. I want to update that column by adding to it, without running a SELECT query to get the number and add it. Is this possible?
update tablename set field = field + 1 where condition
This is a direct MySql update command to do so. You didn't mention if you were using a specific ORM like Hibernate or anything, but this same concept can be applied in HQL etc.

Categories