I'm working on a proof of concept to convert our project to a Spring Boot application. I have a repository class with 2 methods: save and find.
@Repository
public class UserDataRepo {
private EntityManager em;
public boolean save(UserDataModel model) {
try {
UserDataModel existingModel = find(model.getTable(), model.getFieldName();
model.setId(existingModel.getId());
this.em.merge(model);
this.em.flush();
return false;
} catch (NoResultException e) {
this.em.persist(model);
this.em.flush();
return true;
}
}
public UserDataModel find(String table, String field) {
Query query = this.em.createQuery(FIND_USERDATA_STATEMENT);
query.setParameter("table", table);
query.setParameter("fieldName", field);
return (UserDataModel) query.getSingleResult(); // throws NoResultException
}
}
In my Spring Boot Application class, I have added @EnableJpaRepositories
, @EnableTransactionManagement
. My application starts up fine without any errors. But as you can see the save method depends on the find method to determine whether to merge or persist. If there is no record, find method throws NoResultException. What I'm observing is it never falls inside the save method's catch block. Spring Boot just throws an error saying NoResultException.
In the case of merge, it works like a charm. So it means the entity manager works fine.
I do not know what else needs to be configured. Any thoughts?
Adding error from the logs:
org.springframework.dao.EmptyResultDataAccessException: No entity found for query; nested exception is javax.persistence.NoResultException: No entity found for query
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:389)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:223)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)