问题
假设mysql中有一张product_category
表,它有以下列
- category_id 主键自增
- category_name 类目名 (not null)
- category_type 类目编号 (not null)
且存在一条记录
category_id | category_name | category_type |
---|---|---|
1 | 水果 | 12 |
// 实体对象类
@Entity
@Data
public class ProductCategory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer categoryId;
private String categoryName;
private Integer categoryType;
}
假如只改其中某一列的内容,其他不变
// Dao层测试
Optional<ProductCategory> result = repository.findById(1);
ProductCategory productCategory = result.isPresent() ? result.get() : null;
productCategory.setCategoryType(4);
ProductCategory updateResult = repository.save(productCategory);
看起来似乎没什么问题,运行后去数据库中查看时变成了这样
category_id | category_name | category_type |
---|---|---|
1 | ??? | 12 |
打印的sql执行语句为
Hibernate: select productcat0_.category_id as category1_0_0_, productcat0_.category_name as category2_0_0_, productcat0_.category_type as category3_0_0_ from product_category productcat0_ where productcat0_.category_id=?
Hibernate: select productcat0_.category_id as category1_0_0_, productcat0_.category_name as category2_0_0_, productcat0_.category_type as category3_0_0_ from product_category productcat0_ where productcat0_.category_id=?
Hibernate: update product_category set category_name=?, category_type=? where category_id=?
解决方法
从上面的问题可知,即便我们只修改某一个字段,jpa进行更新的时候也会更新其他的未修改的字段。
使用@DynamicUpdate注解
在实体对象类前加上@DynamicUpdate注解后,hibernate的sql更新语句就不会包含未修改的字段了。
@Entity
@Data
@DynamicUpdate
public class ProductCategory {
...
}
再次运行后的sql语句为
Hibernate: select productcat0_.category_id as category1_0_0_, productcat0_.category_name as category2_0_0_, productcat0_.category_type as category3_0_0_ from product_category productcat0_ where productcat0_.category_id=?
Hibernate: select productcat0_.category_id as category1_0_0_, productcat0_.category_name as category2_0_0_, productcat0_.category_type as category3_0_0_ from product_category productcat0_ where productcat0_.category_id=?
Hibernate: update product_category set category_type=? where category_id=?