springboot+postgresql+mybatisplus 整合的一些坑
一、自定義TypeHnadler的使用
自定義的TypeHandler主要是轉換Jsonb和array等類型
如果是使用mybatisplus的內置方法,則需要在實體字段加上@TableField注解,並且需要在類名上啟動@TableName(autoResultMap = true)
// autoResultMap = true 必須寫,否則無法識別 @TableName(autoResultMap = true) public class BlogUser implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String name; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime createTime; private Integer version; // 使用類型轉換,否則無法增刪改查 @TableField(typeHandler= JsonTypeHandler.class) private Map<String,Object> relation; }
如果是寫在xml里面,則必須在對應字段注明轉換器class:
<insert id="addxml" parameterType="com.hou.postgresql.blog.entity.po.BlogUser"> INSERT INTO blog_user (name, relation, fans, birthday, points, login_time, write_interval, numbers, adult, address, weight) VALUES (#{name}, /*必須顯式的指明轉換器,否則編譯過程就會報錯,主要是List,map這種數組,jsonb對應的實體類型*/ #{relation,typeHandler=com.hou.postgresql.handler.JsonTypeHandler}, #{fans,typeHandler=com.hou.postgresql.handler.ArrayTypeHandler}, #{birthday}, #{points}, #{loginTime}, #{writeInterval}::interval, #{numbers,typeHandler=com.hou.postgresql.handler.ArrayTypeHandler}, #{adult}, #{address}, #{weight}) </insert>
column is of type jsonb but expression is of type character varying問題
即使寫了轉換器,查詢的時候沒問題,但是插入的時候依然會報這個錯,這時需要在連接的url后面加上參數stringtype=unspecified就可以正常添加了
url: jdbc:postgresql://192.168.1.11:5432/postgres?currentSchema=sys&stringtype=unspecified
二、schemas問題
pgsql默認的是public,如果用mybatisplus的內置方法的話,是需要指定連接的currentSchema的,否則只會默認查詢public,自己寫sql可以在前面加上schemas
但是使用內置方法沒有,必須在連接url指定schemsa,否則會報ERROR: relation "item" does not exist表不存在
三、所有數據類型參數格式
url后面加上stringtype=unspecified就可以使用任意格式插入了,除了json和array之外,其他的特殊類型,比如地址,間隔,時間等都可以使用string
參數如下:
{ "address": "192.168.1.70", // inet "adult": false, // boolean "birthday": "1994-12-16", // date "fans": ["zhangpeng","zhouhang","pengle"], "loginTime": "09:12", // time "name": "侯征", "numbers": [12,56,42], // array "points": 10.522, // numeric "relation": { // jsonb "key": "value" }, "weight": "[45,50]", // 區間 "writeInterval": "800" // 時間間隔,單位秒 }