Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put JSONB throught Postgres database with JPA

I am trying to build an REST application using Jersey, Gson, JPA and I would like to put a JSON object to JSON or JSONB database field into Postgres.

I tried to do something like this : How to use Postgres JSONB datatype with JPA? but my table see a 'VARCHAR' type instead of 'JSONB'.

My Entity :

@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 entity :

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);

Method insertVotes :

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();

}

Method create of crudServiceBean.create :

public  <T> T create(T t) {
    this.em.persist(t);
    this.em.flush();
    this.em.refresh(t);
    return t;
}

My JPA provider create my the 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 to use Hibernate.

Thank you.

like image 400
Pierre Rol Avatar asked May 15 '17 09:05

Pierre Rol


People also ask

How does Postgres store Jsonb?

The json data type stores an exact copy of the input text, which processing functions must reparse on each execution; while jsonb data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed.

Should I use Jsonb in Postgres?

JSONB supports indexing the JSON data, and is very efficient at parsing and querying the JSON data. In most cases, when you work with JSON in PostgreSQL, you should be using JSONB.


1 Answers

I have finally found the problem. I have forgetten this line on my attribute :

@Column (nullable = true, columnDefinition = "jsonb")
like image 75
Pierre Rol Avatar answered Sep 28 '22 07:09

Pierre Rol