jeudi 2 janvier 2020

Store jsonb in database through reflection

SimpleJson s = new SimpleJson(UUID.randomUUID(), new JsonBean("1d1", "zanzibar")); save(s);

`save(SimpleJson s){

Fields are coming from "Field[] attributeClass = entityClass.getDeclaredFields();" attributeClass = [id,jsonBean,date_add,date_update] Values are managed through refelection like below: for (Field fieldKey : attributeClass) { value = getValue(valueKeys, fieldKey.getName());

                    if(value != null){

                        if(!first){
                            sb.append(",");
                            sbValues.append(",");
                        }
                        sb.append(getFieldName(fieldKey));

                        sbValues.append("?");
                        values.add(normalizeValue(value));

                        first = false;
                    }
                }

protected Object normalizeValue(Object value) {

    if (value == null)
        return value;

    if(value instanceof UUID) {
        return value;
    }else if(value instanceof LocalDateTime){
        return Timestamp.valueOf((LocalDateTime)value);
    }else if(value instanceof LocalDate){
        return Date.valueOf((LocalDate)value);
    }else if(value instanceof Instant){
        return ((Instant)value).toEpochMilli();
    }else if(value instanceof LocalTime){
        return Time.valueOf((LocalTime)value);
    }else if(value instanceof RevoObject<?>){
        return ((RevoObject<?>) value).getKey();
    }else if(value instanceof Double){
        return value.toString();
    }else if(value instanceof Object) {
        return JSON.toJson(value);
    }else{
        return value;
    }
}

}`

Which result its'coming after hovering:

INSERT INTO test_simple_json(id,jsonBean,date_add,date_update)VALUES( '53052bfe-7464-40c8-adf7-6e90a2361f17', '{"id":"1d1","name":"zanzibar"}', '2020-01-02 15:27:42.609','2020-01-02 15:27:42.61

)

but it should be :jsonBean should be "jsonBean" like below:

INSERT INTO test_simple_json(id,"jsonBean",date_add,date_update)VALUES( '53052bfe-7464-40c8-adf7-6e90a2361f17', '{"id":"1d1","name":"zanzibar"}', '2020-01-02 15:27:42.609','2020-01-02 15:27:42.61

)

Error i am getting:

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [INSERT INTO test_simple_json(id,jsonBean,date_add,date_update)VALUES( ?,?,?,?); ]; nested exception is org.postgresql.util.PSQLException: ERROR: column "jsonbean" of relation "test_simple_json" does not exist





Aucun commentaire:

Enregistrer un commentaire