openJPA 遭遇PG 之 like 语法问题

iT商城的转pg 测试进入代码修改阶段 ,

openjpa 还是有写问题的。

sql语句:  select * from tab  t where t.type like ‘%config.%' 

我们java 代码里的写法是这样的  “ cyp_nw_app=> select * from ENT_CONSTANTS where lower(type) like '%config.%' ”

在PG 中执行的时候,就变成了 :
[code]
 cyp_nw_app=> select * from ENT_CONSTANTS where lower(type) like '%config.%' escape '\\';  
[/code]

而且还报错了:
ERROR:  invalid escape string
HINT:  Escape string must be empty or one character.

这个问题还是要从pg 9.1 版本的改变说起:

9.0 之前的版本里  pg 的参数 standard_conforming_strings  默认值是off

也就是我们我们常规意义上的在oracle 里的写法 “ cyp_nw_app=> select * from ENT_CONSTANTS where lower(type) like '%config.%' ”  是可以运行的, openjpa 在运行时做了包装变成了“select * from ENT_CONSTANTS where lower(type) like '%config.%' escape '\\';   ”  是可以运行在pg上的。 

pg9.1版本把这个参数默认修改为 standard_conforming_strings  =on 
PG的文档给出了一个解释:
{  If the configuration parameter standard_conforming_strings is off, then PostgreSQL recognizes backslash escapes in both regular and escape string constants. However, as of PostgreSQL 9.1, the default is on, meaning that backslash escapes are recognized only in escape string constants. This behavior. is more standards-compliant, but might break applications which rely on the historical behavior, where backslash escapes were always recognized. As a workaround, you can set this parameter to off, but it is better to migrate away from using backslash escapes. If you need to use a backslash escape to represent a special character, write the string constant with an E. }

这个问题 ,目前在openjpa  2.0.0  2.0.1  2.1.1  3个主要版本中都存在。

那么怎么办呢?  关闭pg 的参数是一个选择,似乎不是很明智。
另一个就是修改java 代码的写法了

一个方式 java 代码里直接写上 escape 语法 : 
sql= ” select * from ENT_CONSTANTS where lower(type) like '%config.%' escape '\\' “

或者 sql = ” select * from ENT_CONSTANTS where lower(type) like '%config.%' escape E'\\' "
注意这个E 是pg 里escape 的语法。 这样基本的问题就解决了。

如果直接在Psql 里 运行的话 就要写下面带E 的那个了

或者 escape  '\'   注意只有一个 \ .

就这个sql 本身还有很多可以改进的地方:

如果根据这个sql 的功能,改写为更加PG的方式,我会写为:

sql=" select * from ENT_CONSTANTS where  type  ~*  E'config.' "

至少不用对每行都做lower()的函数运算了。 ~  ~*  是pg 里正则表达的运算符  ~* 不区分大小写。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/133735/viewspace-719220/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/133735/viewspace-719220/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值