简体   繁体   English

如何防止 Spring 数据 JPA 中的自动更新?

[英]How prevent update automatically in Spring Data JPA?

I have a JPA entity as follow:我有一个 JPA 实体如下:

@Entity
@DynamicUpdate
@TypeDef(name = "json_binary", typeClass = JsonBinaryType::class)
public class Workflow {
   private Long id;
   private String name;

   @Type(type = "json_binary")
   @Column(columnDefinition = "jsonb")
   private List<AccessModel> users;
}

public class AccessModle {
   private String name;
   private Int permission;
}

And the repository:和存储库:

@Repository
public interface WorkflowRepository extends JpaRepository<Workflow, Long> {}

Now when I just want to find a workflow (repository.findById(1)), The hibernate log is as follow:现在当我只想找到一个workflow (repository.findById(1))时,hibernate 日志如下:

Hibernate: select workflow0_.id as id1_12_0_, workflow0_.name as name2_12_0_, 
           workflow0_.users as users3_12_0_ where workflow0_.id=?
Hibernate: update workflow set users=? where id=?

I didn't modify users , But Hibernate set it.我没有修改users ,但是 Hibernate 设置了它。 How can I prevent automatically update entity?如何防止自动更新实体?

Update:更新:

@Service
@Transactional
public class WorkflowServiceImpl {

    @Autowired
    private WorkflowRepository repository;

    public Workflow find(Long id) {
        return repository.findById(id);
    }
}

You have added @Transactional at service level so, it will be applicable for each method present in the service class.您已在服务级别添加了@Transactional ,因此它将适用于服务 class 中存在的每种方法。 You need to add @Transactional(readOnly = true) on your find(Long id) method.您需要在find(Long id)方法上添加@Transactional(readOnly = true) It will solve your problem.它会解决你的问题。

@Service
@Transactional
public class WorkflowServiceImpl {

    @Autowired
    private WorkflowRepository repository;

    @Transactional(readOnly = true)
    public Workflow find(Long id) {
        return repository.findById(id);
    }
}

It is best practice to add the @Transactional on required methods only instead at the class level.最佳做法是仅在所需方法上添加@Transactional ,而不是在 class 级别。

You can include the following properties ( insertable = false, updatable = false ) along with the definition for @Column --您可以在@Column的定义中包含以下属性 ( insertable = false, updatable = false ) --

@Column(columnDefinition = "jsonb", insertable = false, updatable = false)

This will prevent from inserting or updating the value for the users这将防止插入或更新users的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM