重写SaveAll的逻辑?

huangapple go评论82阅读模式
英文:

Logic to override SaveAll?

问题

根据数据库中的某个值(而不是主键),我想要覆盖saveAll函数。

@Repository
public interface ConfluencePageRepository extends CrudRepository<ConfluencePageReport, Long> {

}

我们从CRUDRepository获得了saveAll(List list)函数,我希望它像往常一样保存所有实体,但在保存之前要检查特定的值。

如果该实体在数据库中不存在,这就是我想要自定义该函数的原因。

英文:

I would like to override the saveAll function depending on a value in the Database (not the primary Key).

@Repository
public interface ConfluencePageRepository extends CrudRepository&lt;ConfluencePageReport, Long&gt; {

}

We got the function saveAll(List list) from the CRUDRepository, and I would like it to save all my entities as it does but check before by a specific value.

If this entity doesn't exist in the DB, that is why I would like to customize the function.

答案1

得分: 3

这是一个糟糕的想法,你应该重新考虑你的方法。顺便说一下,在服务层进行此类操作是合适的,而且要在事务的上下文中进行。

另外,按照你计划的方式检查值是否存在于数据库中是不建议的。如果有不同的线程同时持久化相同的数据集,很可能会得到不一致的数据。

最后,除非你获取了表级别的锁(我认为你不想要那样),最好在数据库中创建约束,然后在你的服务层处理异常(比如 DataIntegrityViolationException)。

英文:

This is a bad idea and you should rethink your approach. By the way, this is the type of thing you want to do in the service layer, in the context of a transaction.

Also, you are not advised to check if the value exists in the database in the way you are planning to do. If you have different threads persisting the same set of data at the same time, you’ll likely to end up with inconsistent data.

Finally, unless you acquire a table-level lock (I don’t think you want that), you’d better create constraints in the database and then handle exceptions (such as DataIntegrityViolationException) in your service layer.

huangapple
  • 本文由 发表于 2020年10月26日 15:49:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64533180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定