Home > Enterprise >  Save and retrieve database entity across 2 services in Spring Boot
Save and retrieve database entity across 2 services in Spring Boot

Time:02-24

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);
}

CodePudding user response:

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);
}


CodePudding user response:

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);
}

  • Related