Spring data JPA transaction simple Isolation(READ_UNCOMMITTED,READ_COMMITTED,REPEATABLE_READ) example 1.
I create a test class and write three method.
First method will save a new user to database.I started the first method in debug mode and add a debug point in
package org.springframework.data.jpa.repository.support.SimpleJPARepository.
The SimpleJPARepository is the default implementation of Spring Data JPA repository interfaces.
Breakpoint in save method .
this line(this.em.persist(entity)). provides persist of user object
public class SimpleJpaRepository<T, ID extends Serializable>
public class SimpleJpaRepository<T, ID extends Serializable>
implements JpaRepository<T, ID>, JpaSpecificationExecutor<T> {
...
@Transactional
public <S extends T> S save(S entity) { if(this.entityInformation.isNew(entity)) { this.em.persist(entity); //AbstractEntityManagerImpl persist method return entity;//BreakPoint HERE } else { return this.em.merge(entity); } }
.....
}
Create a test class.
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class)
@Test@Transactional
public void testIsolation() {
User user = createNewUser(); userRepository.save(user); } public User createNewUser() { return new User("name", "surname", "tarikTRR", "tarik"); } @Test@Transactional(isolation = Isolation.READ_UNCOMMITTED) public void readUnCommittedValue(){ User user=userRepository.findByUsername("tarikTRR"); assertTrue(user != null); }....}First run testIsolation method in debug mode.You put a break point in save method.Soit will wait the method.Dont press F6.Now the object is persist.No user object in databaseThen run readUnCommittedValue method in debug mode or run mode.You will see user object.It is not null.@Test@Transactional(isolation = Isolation.READ_COMMITTED) public void readUnCommittedValue(){User user=userRepository.findByUsername("tarikTRR"); assertTrue(user != null); }}We repeat the same scenario with READ_COMMITTED.Result user object is null.Because user entity is not committed in Database.
We repeat the same scenario with REPEATABLE_READ.User object is null.
Summary:
1)Write test methods.
2)Put break point in save method (line:return entity;).The method is in SimpleJpaRepository.
3)Run createNewUser() method in debug mode .Dont press F6 when Code is on this line(line:return entity;).
4)Now object is persist.
5-1) Run readUnCommitted() method with(Isolation.READ_UNCOMITTED)
6-1)You will see result.User object is not null.Because this transaction will read uncomitted object.
5-2)Run readUnCommitted() method with(Isolation.READ_COMITTED)
6-2)You will see result.User object is null.Because this transaction will read only committed object.
5-3)Run readUnCommitted() method with(Isolation.REPEATABLE_READ)
6-3)You will see result.User object is null.Because this transaction will read only committed object.
Comments
Post a Comment