在postgresql的使用jsonb數(shù)據(jù)結(jié)構(gòu)救巷,存儲的是一個json array壶熏,當(dāng)查詢使用包含某個字符串的時候,要用到 ? 操作符浦译。
例如 select * from table where jsonb_column ? 'string'
結(jié)合mybatis的xml一起使用的時候棒假,會誤把 ? 操作符當(dāng)作preparestatement的參數(shù)占位符,因此報錯:
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.postgresql.util.PSQLException: 未設(shè)定參數(shù)值 2 的內(nèi)容精盅。
### The error may exist in User.xml
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: seelct * from table where jsonb_column ? ?
### Cause: org.postgresql.util.PSQLException: 未設(shè)定參數(shù)值 2 的內(nèi)容帽哑。
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:122)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:113)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:73)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:69)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53)
at com.sun.proxy.$Proxy2.getCount(Unknown Source)
at org.beiyu.study.mybatis.MyBatisTest.testMb(MyBatisTest.java:29)
at org.beiyu.study.mybatis.MyBatisTest.main(MyBatisTest.java:18)
在https://jdbc.postgresql.org/documentation/head/statement.html可以看到解決辦法,使用 ?? 轉(zhuǎn)義即可叹俏。
In JDBC, the question mark (?) is the placeholder for the positional parameters of aPreparedStatement.
There are, however, a number of PostgreSQL operators that contain a question mark. To keep such
question marks in a SQL statement from being interpreted as positional parameters, use two question marks
(??) as escape sequence. You can also use this escape sequence in aStatement, but that is not required.
Specifically only in aStatementa single (?) can be used as an operator.