gpt4 book ai didi

mysql - 如何用Mybatis在MySQL的插入语句中获取默认为CURRENT_TIMESTAMP的字段值

转载 作者:行者123 更新时间:2023-11-28 23:19:35 26 4
gpt4 key购买 nike

我在 MySQL 中有一个表如下:

CREATE TABLE `mytable` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`phone` VARCHAR(128) NULL DEFAULT NULL,
`createTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=25
;

我有一个 Mybatis 映射器,如下所示

@Mapper
public interface MyMapper {
Integer insertRecord(List<PhoneModel> list);
}


<insert id="insertRecord" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert into mytable(phone) values
<foreach item="item" index="index" collection="list" separator=",">
(#{item.phone})
</foreach>
</insert>

PhoneModel中有3个属性:id,phone,createTime。现在我可以在调用 insertRecord 后得到 id,但我也想得到 createTime

我已经完成了 documents在 Mybatis 上。它提到我可以将多个属性名称(例如 createTime)添加到 keyPropertykeyColumn

keyProperty (insert and update only) Identifies a property into which MyBatis will set the key value returned by getGeneratedKeys, or by a selectKey child element of the insert statement. Default: unset. Can be a comma separated list of property names if multiple generated columns are expected.

keyColumn (insert and update only) Sets the name of the column in the table with a generated key. This is only required in certain databases (like PostgreSQL) when the key column is not the first column in the table. Can be a comma separated list of columns names if multiple generated columns are expected.

我不清楚以逗号分隔的属性/列名列表 是什么意思。我试过 keyProperty="id, createTime"但它似乎不起作用。

谢谢。

最佳答案

如果 keyProperty="id, createTime" 是您代码的副本,则清除逗号后的空格。无论如何,它可能不是(唯一的)罪魁祸首。

我猜想 auto_increment 的内部操作就像一个序列。而 CURRENT_TIMESTAMP 是一个函数。然后您可以检查多个 keyProperty 支持行为:出于测试目的,您可以添加另一列(auto_increment 、 serial 吗?)以便检查您是否可以获得生成的 key 。

好像PostgreSQL allows RETURNING来自 Insert 的值,但我没有在 MySQL 中找到等效项。

您执行单个多行插入语句,CURRENT_TIMESTAMP 的行为如何?为所有记录插入完全相同的时间戳?还是值(value)观在演变?这可以在插入大量记录时观察到,这将花费超过 1 秒。

为什么不自己插入时间戳?只是批量插入而不是多行插入,在 java 中迭代列表, session 必须使用 ExecutorTYPE.REUSE 只准备语句一次。

for(PhoneModel model : list) {
model.setCreateTime(new Date());
mapper.insertRecord(model);
}

关于mysql - 如何用Mybatis在MySQL的插入语句中获取默认为CURRENT_TIMESTAMP的字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42387576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com