How to host JSONB over Postgres database with JPA
I am trying to create a REST application using Jersey, Gson, JPA and I would like to put a JSON object in a JSON or JSONB database field in Postgres.
I tried to do something like this: How to use the Postgres JSONB datatype with JPA? but my table will see the type "VARCHAR" instead of "JSONB".
My essence:
@Entity
@Table(name = "votes")
public class Votes {
@Id
@GeneratedValue
private int id;
private int idSocialChoice;
@Convert(converter=JsonConverter.class)
private JsonObject vote;
public Votes() {
}
public JsonObject getVote() {
return vote;
}
public void setVote(JsonObject vote) {
this.vote = vote;
}
public int getIdSocialChoice() {
return idSocialChoice;
}
public void setIdSocialChoice(int idSocialChoice) {
this.idSocialChoice = idSocialChoice;
}
How I insert my object:
Votes votes0 = new Votes();
votes0.setIdSocialChoice(3);
JsonObject object = Json.createObjectBuilder().build();
votes0.setVote(object);
List<Votes> listvotes = new ArrayList<Votes>();
listvotes.add(votes0);
ModelEntities.insertVotes(listvotes);
InsertVotes method:
public static void insertVotes(List<Votes> animalList) {
CrudServiceBean crudServiceBean = new CrudServiceBean(CrudServiceBean.PU_DB);
crudServiceBean.newTransaction();
for(Votes votes : animalList)
crudServiceBean.create(votes);
crudServiceBean.commit();
crudServiceBean.closeTransaction();
}
Create a crudServiceBean.create method:
public <T> T create(T t) {
this.em.persist(t);
this.em.flush();
this.em.refresh(t);
return t;
}
My JPA provider creates my schema like this (createDDL_ddlGeneration.sql):
CREATE TABLE votes (ID INTEGER NOT NULL, IDSOCIALCHOICE INTEGER, VOTE VARCHAR(255), PRIMARY KEY (ID))
I would also avoid using Hibernate.
Thank.
+3
source to share