【发布时间】:2014-06-21 23:12:04
【问题描述】:
问题
如何使用jOOQ 创建以下两个(等效)MySQL 语句中的任何一个?
SELECT * FROM `tbl` WHERE `col` = BINARY 'foobar ';
SELECT * FROM `tbl` WHERE `col` = CAST('foobar ' AS BINARY);
背景
我想比较任意字符串,可能包括(重要的)尾随空格。不幸的是,在与= 比较时,默认情况下 MySQL 会忽略尾随空格。据我从this question 看到的,只有使用the BINARY operator in MySQL 才能进行此类比较。
我已经尝试过了
我尝试使用DSL.cast() method in jOOQ:
myDb.selectFrom(TBL)
.where(TBL.COL
.eq(DSL.cast("foobar ", MySQLDataType.BINARY)))
.fetchOne();
// → compiler error: “The method eq(String) in the type Field<String> is not
// applicable for the arguments (Field<byte[]>)”
myDb.selectFrom(TBL)
.where(DSL.cast(TBL.COL, MySQLDataType.BINARY)
.eq("foobar "))
.fetchOne();
// → compiler error: “The method eq(byte[]) in the type Field<byte[]> is not
// applicable for the arguments”
myDb.selectFrom(TBL)
.where(DSL.cast(TBL.COL, MySQLDataType.BINARY)
.eq(DSL.cast("foobar ", MySQLDataType.BINARY)))
.fetchOne();
// → runtime error: “org.jooq.exception.DataTypeException: Cannot convert from
// foobar (class java.lang.String) to class [B”
解决方法
我最后的办法是将查询更改为使用LIKE 而不是=。不过,那将是一个 hack,因为我必须总是先在我的字符串中引用任何通配符,而且我还将面临性能损失:-|
【问题讨论】: