Java – database write lock entity in spring
When I am using its child entity, I need to write lock the parent entity so that it is not allowed to modify (or sparse) the parent entity
Solution
To implement the policy you are looking for, you need to trigger a select for update SQL query on the parent row (for example, select * from parent where id =? For update. This will get a locked select query on the extracted row
>Start trading. > Use select for update to load the parent row. > Update child. > Save the children. > Submit transaction This saves the child and releases the lock on the parent row
You can use spring transactions to enforce transaction boundaries The following will work:
class SomeService { @Transactional public ... someMethod(...) { // Load the parent row using SELECT FOR UPDATE. // Save children. } }
@Transactional will apply transaction semantics around the call to somemethod Note that this method must be exposed for @ transactional to work properly
Executing select for update depends on the accuracy of accessing the database – spring JDBC, spring ORM, spring data JPA, etc Here are some ways to do this using these libraries:
You can simply execute a select for update query using the jdbctemplate class jdbcTemplate. Execute ("select * from parent where row =? For update") should be valid
You must use ORM - specific template classes to enforce locking patterns For example, using hibernate4 hibernatetemplate, you can use hibernatetemplate get(Class< T> entityType,Serializable id,LockMode lock).
You can annotate repository methods with @ lock (lockmodetype. Pessimistic_write) to enforce pessimistic locking when executing queries for example
interface ParentRepository extends CrudRepository<Parent,Long> { @Lock(LockModeType.PESSIMISTIC_WRITE) Parent findOne(Long id); }
I'll do it
One thing you should pay attention to is that if you call this operation too many times at the same time, you will encounter a timeout and may also have a deadlock because the row is locked exclusively You will benefit from the following:
>Locking is kept for a very short time, possibly in the final stage of processing, ensuring that any verification is performed in advance, etc This will ensure a quick release of the lock. > Use concurrent users to test and understand the frequency of timeouts and deadlocks If you see timeouts and deadlocks and don't want users to retry, you can use the functionality provided by the spring retry project to retry the method