我正在尝试编写一个查询 Oracle 11g 数据库的 Spring Boot。
是一个非常简单的
select * from item where item_code = 'abc'
命令。
但是因为数据库对该 id 列使用 CHAR(10),所以我发现我只能在 where 子句中使用 like。基本上所有crudRepository的派生查询都失败了。我不得不跳圈才发现只有
like
有效。
下面是我在接口类中使用的
//itemCode = 'AB1234' in all cases below
public Item findByIdItemCode(String itemCode); //return 0 result
@Query("select r from Item r where r.id.itemCode = 'AB1234'")
public Item findcustomfix(); //return 1 result
@Query("select r from Item r where r.id.itemCode = :itemCode")
public Item findcustom(@Param("itemCode") String itemCode); //return 0 result
@Query("select r from Item r where r.id.itemCode like %:itemCode%")
public Item findcustomLike(@Param("itemCode") String itemCode); //return 1 result
//application.properties
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.OracleDialect
//class itemKey
@Column(name="ITEM_CODE", columnDefinition="CHAR", length = 10)
//@Column(name="ITEM_CODE", columnDefinition="CHAR(10)") //also does not work
private String itemCode;
我已经添加了长度定义,但这似乎仍然不足以让 hibernate 生成考虑固定宽度列的
where ITEM_CODE = 'AB1234 '
子句
我无法继续使用
like
方法,因为它无法区分 AB123 和 AB1234。
有正确的方法吗?
我不知道你使用的工具。
在 Oracle 中,
char
数据类型执行您所经历的操作:用空格填充值,直到最大列长度。例如,如果你确实有这样的价值观,那就可以了
但是,对于长度不同的字符串,
char
很少合适,因为......好吧,你知道为什么 - 问题在使用它们时。
以下是您可能需要考虑的一些选项(严格与 Oracle 相关)。
SQL> create table test (val char(10));
Table created.
SQL> insert into test (val) values ('ABC');
1 row created.
SQL> select val, length(val) len from test;
VAL LEN
---------- ----------
ABC 10
使用实际值,右侧用空格填充:
SQL> select * from test where val = 'ABC ';
VAL
----------
ABC
修剪它:
SQL> select * from test where trim(val) = 'ABC';
VAL
----------
ABC
喜欢:
SQL> select * from test where val like 'ABC%';
VAL
----------
ABC
Rpad它:
SQL> select * from test where val = rpad('ABC', 10, ' ');
VAL
----------
ABC
但是:如果你能负担得起,请修改列的数据类型:
SQL> alter table test modify val varchar2(10);
Table altered.
SQL> desc test
Name Null? Type
----------------------------------------- -------- ----------------------------
VAL VARCHAR2(10)
但是,列的值的长度仍然是 10 个字符(保留空格):
SQL> select val, length(val) len from test;
VAL LEN
---------- ----------
ABC 10
更新一下:
SQL> update test set val = trim(val);
1 row updated.
SQL> select val, length(val) len from test;
VAL LEN
---------- ----------
ABC 3
现在您不必使用任何其他函数或运算符来访问值按原样:
SQL> select * from test where val = 'ABC';
VAL
----------
ABC