'Save and retrieve database entity across 2 services in Spring Boot

I have 2 Java Spring Boot web services - services A and B and a shared MySQL database.

In service A, there is an method to write entity into database when a specific HTTP endpoint is called:

public <T> T saveAndFlushMasterData(T masterDataEntity) {
        if (null != masterDataEntity) {
            em.persist(masterDataEntity);
            em.flush();
        }
        return masterDataEntity;
    }

In service B, there is this logic flow which checks to see if the database contains an entry for the specified email. If the database does not contain the email entry, service B will call service A via HTTP post to create the entry. Service A will call the code mentioned above to persist and flush the entity into database.

List<UserEmails> userEmails = userEmailsRepository.findByEmail(email);

// create user if not exist
if(userEmails.isEmpty()) {
    boolean success = serviceA.createUser(adminUserId, email);
    // check userEmails again
    userEmails = userEmailsRepository.findByEmail(email);
}

Now the issue is in service B, when the second 'userEmailsRepository.findByEmail' is called again, it still returns a list of size 0.

The repository code is:

public interface IUserEmailsRepository extends JpaRepository<UserEmails, Integer>{
    List<UserEmails> findByEmail(String email);
}


Solution 1:[1]

Try this:

@Autowired
private EntityManagerFactory emf;

...

List<UserEmails> userEmails = userEmailsRepository.findByEmail(email);

// create user if not exist
if(userEmails.isEmpty()) {
    boolean success = serviceA.createUser(adminUserId, email);

    emf.getCache().evictAll();

    // check userEmails again
    userEmails = userEmailsRepository.findByEmail(email);
}


Solution 2:[2]

I got it working with the use of Transactional annotation and native query:

public interface IUserEmailsRepository extends JpaRepository<UserEmails, Integer>{
    @Query(
            value = "SELECT * FROM user_emails u WHERE u.email = ?1",
            nativeQuery = true)
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    List<UserEmails> findByEmail(String email);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 codependent
Solution 2 Eugene