2014-09-05 53 views
2

理想情況下,在事情的Java方面使用傑克遜。我已經嘗試了明顯的解決方案:是否可以寫一個數據類型轉換器來處理postgres JSON列?

public class JsonObjectConverter implements Converter<Object, ObjectNode> { 

    private final ObjectMapper mapper = new ObjectMapper(); 

    @Override public ObjectNode from(Object dbo) { 
     try { 
      return dbo != null ? mapper.readValue((String) dbo, ObjectNode.class) : null; 
     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 

    @Override public Object to(ObjectNode uo) { 
     try { 
      return uo != null ? mapper.writeValueAsString(uo) : null; 
     } catch (JsonProcessingException e) { 
      throw new RuntimeException(e); 
     } 
    } 

    @Override public Class<Object> fromType() { 
     return Object.class; 
    } 

    @Override public Class<ObjectNode> toType() { 
     return ObjectNode.class; 
    } 
} 

但是,如果我嘗試使用此我得到的錯誤如下所示:

org.jooq.exception.DataAccessException: SQL [insert into "public"."my_table" ("id", "stuff") values (?, ?)]; ERROR: column "stuff" is of type json but expression is of type character varying 
    Hint: You will need to rewrite or cast the expression. 

因爲jOOQs的但是強制類型安全(這是偉大的,BTW)我不能只添加一個.cast(String.class)並完成。那麼,我是否需要在轉換器中做其他事情,還是應該以不同的方式調用代碼?我目前正在這樣做:

Long id = ... 
ObjectNode stuff = ... 
create.insertInto(MY_TABLE) 
    .set(MY_TABLE.ID, id) 
    .set(MY_TABLE.STUFF, stuff) 
    .execute(); 

和我在我的代碼中的其他地方使用可更新的記錄。

回答

0

你可能不會得到JSON數據類型100%正確,只有一個Converter。理想情況下,你應該使用jOOQ 3.5 org.jooq.Binding實現,這是記錄在這裏:

代碼生成器可以配置爲使用自定義Binding(代替或補充Converters)直接在您的數據庫列上。然後,Binding將處理JDBC級別上的所有必要交互。

+0

是的,升級到3.5是我的待辦事項列表。 – 2014-11-27 09:28:25

4

是的,但是您需要使用Postgres特定的API。在上面的代碼,你需要從/用下面替換的方法:

@Override 
public ObjectNode from(Object databaseObject) { 
    if (databaseObject == null) { return null; } 
    try { 
     PGobject dbo = (PGobject) databaseObject; 
     return mapper.readValue(dbo.getValue(), ObjectNode.class); 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
} 

@Override 
public Object to(ObjectNode userObject) { 
    if (userObject == null) { return null; } 
    try { 
     PGobject dbo = new PGobject(); 
     dbo.setType("json"); 
     dbo.setValue(mapper.writeValueAsString(userObject)); 
     return dbo; 
    } catch (JsonProcessingException|SQLException e) { 
     throw new RuntimeException(e); 
    } 
} 
相關問題