当我的字段为空时,我想从数据库中插入默认值。我使用 Oracle 数据库。
CREATE TABLE "EMPLOYEE"
("COL1" VARCHAR2(800) NOT NULL ENABLE,
"COL2" VARCHAR2(100) DEFAULT NOT NULL 'toto',
CONSTRAINT "PK_EMPLOYEE" PRIMARY KEY ("COL1")
通过一个简单的SQL请求,我们可以这样写:
insert into EMPLOYEE(COL1,COL2) values ('titi', default)
我如何在 Spring 中使用注解 MyBatis 来做到这一点?我必须创建一个 HandlerType 吗?
最佳答案
在映射器 XML 中,动态构建 SQL(当非空时添加 col2 列和值):
insert into employee (col1<if test="col2 != null">, col2</if>)
values (#{COL1}<if test="col2 != null">, #{col2}</if>)
编辑:由于注解中的值必须是常量,我曾经认为注解中不可能有动态 SQL,但我在这里发现了一个技巧:How to use dynamic SQL query in MyBatis with annotation(how to use selectProvider)?并亲自检查。
要在注释中使用动态 SQL this,请用“script”标记将其包围:
@Insert("<script>insert into employee (col1<if test='col2 != null'>, col2</if>)
values (#{COL1}<if test='col2 != null'>, #{col2}</if>)</script>")
在测试中,只需转义双引号 "或将其替换为单引号 '
关于java - 当字段为 null 时使用 MyBatis 添加默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31002805/