简体   繁体   English

DB事务还是Java DAO的方法同步?

[英]DB transaction or Java DAO's method synchronization?

I have Java-based web server, and I also have DAO singleton object with method, whose SQL operations' logic must be synchronized in some way in order to guarantee data integrity (method can be accessed from several Java threads simultaneously). 我有一个基于Java的Web服务器,也有一个带有方法的DAO单例对象,其SQL操作的逻辑必须以某种方式进行同步,以保证数据的完整性(可以同时从多个Java线程访问该方法)。

I was wondering to know whether DB transaction wrapping (serializable level) is better than DAO's method explicit synchronization in server side? 我想知道数据库事务包装(可序列化级别)是否比DAO的服务器端方法显式同步更好

Yes, using transactions is better. 是的,使用事务更好。 With synchronizing in your code, locking on the class, the scope of that lock is your classloader, and standing up a second instance of your application will invalidate your locking, because the two instances are using different locks. 通过同步代码,锁定类,该锁定的范围就是您的类加载器,并且站起来应用程序的第二个实例将使您的锁定无效,因为这两个实例使用的是不同的锁。

With database transactions you can have multiple instances of your application and the database treats all the transactions the same. 使用数据库事务,您可以拥有应用程序的多个实例,并且数据库将所有事务视为相同。

Also with databases you have options like dialing down the isolation level to no higher than what you need for that transaction, or using row-level locking. 此外,对于数据库,您还可以选择诸如将隔离级别下调至不高于该事务所需的级别,或使用行级锁定。 Those are harder to implement in code and you're still stuck with not being able to deploy a second instance. 这些很难用代码实现,并且您仍然无法部署第二个实例。

Depends deeply in what is what you want to synchronize, synchronization is about resources, if you have more than one database in your code, and the data integrity problem is distributed, you need a transaction context, not only declaring it but knowing how to manage it properly. 深度依赖于要同步的内容,同步与资源有关,如果代码中有多个数据库,并且数据完整性问题已分布,则需要事务上下文,不仅要声明它,还要知道如何管理它正确。 Assuming you have a single database and assuming your problem is integrity caused by a possible inconsistency of a SELECT clause with a UPDATE or INSERT clause happening later in the method, The right solution would be a DB transaction and the use of a SELECT FOR UPDATE clause. 假设您只有一个数据库,并假设问题是由于SELECT子句与UPDATE或INSERT子句可能在此方法的后面发生不一致而导致的完整性,那么正确的解决方案是使用DB事务和使用SELECT FOR UPDATE子句。 If your problem is about UPDATE/INSERT of different tables in the same operation you may have two resources, one is including CONSTRAINTS, this is the preferred method, but in some cases is not possible. 如果您的问题是关于同一操作中不同表的UPDATE / INSERT,那么您可能有两种资源,一种是包含CONSTRAINTS,这是首选方法,但是在某些情况下是不可能的。 In the case that a CONTRAINT is not possible, consider a redesign of your DATAMODEL as managing this kind of problems synchronyzing app code is the worst solution, but even so is a solution. 如果无法使用CONTRAINT,请考虑重新设计DATAMODEL,因为管理此类问题是同步应用程序代码是最糟糕的解决方案,但即使这样也是一个解决方案。

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

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