aSoler
aSoler

Reputation: 145

How to store a JSON string as entity's attribute

I'm making a game (trying...) like Risk for college with Spring MVC. I'm using JPA and I need to save the state of the game (whose player turn is, units in countries,etc.) in a String field coded with JSON, and that's what's driving me crazy. First, I create the game with other information (id, user's owner, state...) and when It starts for the first time I want to generate the JSON and set it to the entity and save it. I tried with entityManager.merge(game) but when I look at the DB the JSON field is null. I tried to make namedquery and nativequery but at the JSON string have " it's a mess. Any ideas why it's not saving with merge? The code is something like:

HomeController.class

public String getGame(@PathVariable("idGame") long idGame,
        Model model) throws IOException {           
        Game g = GameDao.getGame(idGame);
        if  (g.getJson == null) {
            g.initializeGame(); // it sets the json attribute
            GameDao.update(entityManager, g);
        }
}

GameDAO.class

@Transactional
public static Game update(EntityManager entityManager, Game g) {
    try {       
        entityManager.merge(g); // if I debug here g has the json attribute setted
        return entityManager.find(Game.class, g.getId()); // the game object that's returned hasn't the json field setted
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

This is the repo https://github.com/alvardsoler/reinvasion but it's the most in Spanish. It's for september exams and I don't have too much time so I want to do it very sketchy first, and then if I have time I'll do it good. If I can't save the JSON info in the DB I will save it in a file in the server with the id of the game or something like that.

Upvotes: 0

Views: 1255

Answers (2)

aSoler
aSoler

Reputation: 145

I found the problem. I make the update with createNativeQuery:

Query q = entityManager.createNativeQuery("update Game g SET   g.json=:json where g.id=:id");
q.setParameter("json", g.getJson());
q.setParameter("id", g.getId());
q.executeUpdate();

And added @Transactional in the GameDAO's method and in the HomeController method...

Upvotes: 1

Phiwa
Phiwa

Reputation: 319

It is rather easy using the library GSON (jsonString ):

// Create the JSON string like this first

MyObject yourObject = /* Create an object here */;
Gson gson = new Gson();
String jsonString = gson.toJson(yourObject);


// Create an object from the JSON string like this afterwards
MyObject newObject = gson.fromJson(jsonString , MyObject.class);

Upvotes: 0

Related Questions