[英]How prevent update automatically in Spring Data JPA?
我有一個 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;
}
和存儲庫:
@Repository
public interface WorkflowRepository extends JpaRepository<Workflow, Long> {}
現在當我只想找到一個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=?
我沒有修改users
,但是 Hibernate 設置了它。 如何防止自動更新實體?
更新:
@Service
@Transactional
public class WorkflowServiceImpl {
@Autowired
private WorkflowRepository repository;
public Workflow find(Long id) {
return repository.findById(id);
}
}
您已在服務級別添加了@Transactional
,因此它將適用於服務 class 中存在的每種方法。 您需要在find(Long id)
方法上添加@Transactional(readOnly = true)
。 它會解決你的問題。
@Service
@Transactional
public class WorkflowServiceImpl {
@Autowired
private WorkflowRepository repository;
@Transactional(readOnly = true)
public Workflow find(Long id) {
return repository.findById(id);
}
}
最佳做法是僅在所需方法上添加@Transactional
,而不是在 class 級別。
您可以在@Column
的定義中包含以下屬性 ( insertable = false, updatable = false
) --
@Column(columnDefinition = "jsonb", insertable = false, updatable = false)
這將防止插入或更新users
的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.