java - 如何将 hibernate @DynamicUpdate 与 spring data jpa 一起使用?

标签 java spring hibernate spring-data-jpa

我正在使用 spring data-jpa。我只想更新一列。

我的仓库是;

public interface UserRepository extends JpaRepository<User,Long> {
}

我的服务是;

public User save(User user) {
    return userRepository.save(user);
}

我的实体;

@Entity
@DynamicUpdate(true)
public class User implements Serializable {
    // column definitions, etc.
}

如何只更新 User 中的一列?

最佳答案

首先,我想解释一下为什么 @DynamicUpdate 不适合您。所以我应该注意 @DynamicUpdate 是如何工作的:

The @DynamicUpdate annotation is used to specify that the UPDATE SQL statement should be generated whenever an entity is modified. By default, Hibernate uses a cached UPDATE statement that sets all table columns. When the entity is annotated with the @DynamicUpdate annotation, the PreparedStatement is going to include only the columns whose values have been changed.(more details)

例如,假设 User 有一个名为 name 的属性。

因此,如果您第一次使用已定义的名称保存用户,现在您将 null 作为值传递给 @DynamicUpdate 将假定它是一个更改并尝试将名称更新为 null

第一种解决方案:

作为第一个解决方案,如果你想让@DynamicUpdate 工作,首先你应该用旧值填充所有其他User 属性,然后你可以保存它。

优点:生成的 SQL 查询只会更新您想要的属性。

缺点:Hibernate 每次都必须生成相应的 SQL 字符串,因此在 Hibernate 端会产生性能成本。

第二种方案:

您可以使用自定义查询更新用户:

@Modifying
@Query("UPDATE User SET name=(:name) WHERE id=(:id)")
public void updateName(@Param("name")String name, @Param("id")Long id);

第三种方案:

作为最后一个解决方案,我建议您使用 updatable = false。这将在实体插入的第一刻填充该属性。

  @Column(name = "create_date", nullable = false, updatable = false)
    private Instant createDate;

关于java - 如何将 hibernate @DynamicUpdate 与 spring data jpa 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52162452/

相关文章:

java - 创建一个原始 int 列表?

java - Spring查询字符串简单验证?

java - 如何从静态实例的 bootstrap.yml 文件中获取值

java - 如何在 Spring/MyBatis 中使用事务?最佳实践?

java - Wicket 测试 - AnnotApplicationContextMock - 没有应用程序附加到当前线程主线程

java - 我的双向 JPA OneToMany 映射感觉很奇怪

java - 我想读取一个 Excel 文件并将数据上传到 PostgresDB 中的一个表中

java - 如何在 AutoCompleteTextView 中基于另一个数组值显示(突出显示)值?

java - 标准方法名,为什么println中的l不是大写?

java - Docker 环境变量中的 Spring 属性