1

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.

Laodao
  • 1,547
  • 3
  • 17
  • 39
  • 2
    Something like `UPDATE YOUR_TABLE SET VALUE = VALUE + 1` directly in the database. – Arnaud Denoyelle Aug 21 '17 at 15:00
  • 1
    Note : you might need to know who "liked" (and prevent from liking multiple times). So another solution would be to store all the likes (maybe in a non-relational database). When a user likes, you insert a "like" in your "likes" table. When you need to know the "like count", just perform a sum. – Arnaud Denoyelle Aug 21 '17 at 15:18

2 Answers2

3

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
  • Thanks for your reply. Is this querydsl sql an atomic operation? Or do I need to make the method synchronized? – Laodao Aug 22 '17 at 12:33
  • Well the `UPDATE` is atomic so you don't need to bother with synchronizing the Java method. –  Aug 22 '17 at 12:34
1

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 !

Alexi Courieux
  • 92
  • 2
  • 11