Search code examples
javapostgresqlquerydsl

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


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.


Solution

  • 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