vignesh
vignesh

Reputation: 466

How to handle an Entity in JPA with Single Instance?

Hi Im new to JPA I want to know how to handle the following scenario

I need to maintain in database the total count of messages received, there is no need to store messages but only its count.Im representing count by an Entity called MessageCount having a variable count as follows

    @Entity  
    public class MessageCount  
    {  
        long count;
    ...

I need to update count whenever i recieve a message.

How can i update it ?
What will be the correct approach to handle this ?

Thanks in Advance .

Upvotes: 1

Views: 175

Answers (1)

Colin M
Colin M

Reputation: 13348

The only way to reliably (read: atomically) do this is to issue a direct query (as opposed to fetching the entity and incrementing it). The appropriate JPA query would be:

UPDATE MessageCount SET count = count + 1

If you fetch the entity with JPA, add 1, and save it again - you risk overwriting the value that another thread has incremented and saved. Performing the operation in a single query ensures that it happens in a single, atomic transaction.

Upvotes: 2

Related Questions