@DynamicInsert属性:设置为true,设置为true,表示insert对象的时候,生成动态的insert语句,如果这个字段的值是null就不会加入到insert语句当中.默认false。

@DynamicUpdate属性:设置为true,设置为true,表示update对象的时候,生成动态的update语句,如果这个字段的值是null就不会被加入到update语句中,默认false。

建表语句:

CREATE TABLE `product_category` (
    `category_id` INT(11) NOT NULL AUTO_INCREMENT,
    `category_name` VARCHAR(64) NOT NULL COMMENT '类目名字' COLLATE 'utf8mb4_unicode_ci',
    `category_type` INT(11) NOT NULL COMMENT '类目编号',
    `create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
    PRIMARY KEY (`category_id`)
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB
AUTO_INCREMENT=3
;
@Test
public void updateTest() {
ProductCategory category = repository.findOne(2);
category.setCategoryType(8);
repository.save(category);
}

不加DynamicUpdate注解

update product_category set category_name=?, category_type=?, create_time=?, update_time=? where category_id=?

发现数据库update_time值没有变化,原因是update_time还是用的当前对象的。

加上DynamicUpdate注解时,如果数据没变化,则不执行update语句。

如果数据发生变化,更新update语句如下:

update product_category set category_type=? where category_id=?

此时数据库update_time值发生了变化,原因由于更新语句没有提供update_time,因此DDL语句ON UPDATE CURRENT_TIMESTAMP会用当前时间值更新字段。

01-13 07:29
查看更多