user3598272
user3598272

Reputation: 145

JPA+EJB not managed entity in websocket communication

  1. Browser and server connected with websocket
  2. After connected, browser will send data, and handled in server by method 'firstMessage'. This method will store Player entity to variable named 'player' and change its data (it work fine, the database is change )
  3. Next, the browser send data again handled in server by method 'secondMessage'. It change the Player entity data that already stored before. the data is change, but the problem is the database not changing

    @Singleton
    @Startup
    public class Engine {
    
    @Inject DaoPlayer daoPlayer;
    Player player;    
    
    public void firstMessage(clientId){
        player = daoPlayer.findById(clientId);
        player.coin = 3;
    }
    
    public void secondMessage(){
        player.coin = 999;
    

    }

Problem :

Change in Player entity inside method 'secondMessage' not updating the database

What i try so far :

Upvotes: 0

Views: 258

Answers (1)

Steve C
Steve C

Reputation: 19445

What you are trying to do is not possible.

You need to code secondMessage as

public void secondMessage() {
    player.coin = 999;
    player = daoPlayer.merge(player);
}

Your first method works because the player object remains part of the current persistence context until the transaction is completed (possibly when the method returns).

The second method cannot work because the player is no longer a part of any persistence context. The merge operation merges it back into a persistence context, possibly returning a different instance if it had been loaded earlier in your call chain.

Upvotes: 1

Related Questions