Fawzan Fawzan - 11 months ago 84
Java Question

Persisting a JSON Object using Hibernate and JPA

I am trying to store a JSON object in MySQL database in spring boot. I know I am doing something wrong but I a can't figure out what it is because I am fairly new to Spring.

I have a rest endpoint where I get the following JSON object (via HTTP PUT) and I need to store it in database so that the user can fetch it later (via HTTP GET).

{
"A": {
"Name": "Cat",
"Age": "1"
},
"B": {
"Name": "Dog",
"Age": "2"
},
"C": {
"Name": "Horse",
"Age": "1"
}
}


Note that in the above case The number of keys in the object may vary, Due to that requirement I am using a
HashMap
to catch the object in the controller.

@RequestMapping(method = RequestMethod.POST)
public String addPostCollection(@RequestBody HashMap<String, Animal> hp) {

hp.forEach((x, y) -> {
postRepository.save(hp.get(x));
});

return "OK";

}


As you can see in the method, I can iterate the
HashMap
and persist each
Animal
object in db. But I am looking for a way to persist the entire
HashMap
in a single record. I have did some reading and they suggest me to use a
@ManyToMany
mapping.

Can anyone point me in a direction to persist the
HashMap
in a different way? (or is using the
@ManyToMany
the only and right way to do this?)

Answer Source

Your JSON is well structered, so usually theres no need to persist the entire map in one single record. You won't be able to use the Hibernate/JPA query functions and a lot more.

If you really want to persist the entire map in one single record, you could persist the map in its string representation and, as already proposed, use a JSON parser like Jackson to rebuild your HashMap

@Entity
public class Animals {

  private String animalsString;

  public void setAnimalsString(String val) {
    this.animalsString = val;
  }

  public String getAnimalsString() {
    return this.animalsMap;
  }

  public HashMap<String, Animal> getAnimalsMap() {
    ObjectMapper mapper = new ObjectMapper();
    TypeReference<HashMap<String,Animal>> typeRef = new TypeReference<HashMap<String,Animal>>() {};
    return mapper.readValue(animalsString, typeRef); 
  }

}

Your animal class:

public class Animal {

  private String name;
  private int age;

  /* getter and setter */
  /* ... */
}

And you could change your controller method to

@RequestMapping(method = RequestMethod.POST)
public String addPostCollection(@RequestBody String hp) {
  Animals animals = new Animals();
  animals.setAnimalsString(hp);
  animalsRepository.save(hp);
  return "OK";
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download