I am using spring data/jpa to perform some database operations. I have a while loop which runs and successfully inserts data as it runs, but i also need an update operation to happen at the end of each run of a while loop. Here is basically what I have in a simple example. This is exactly the structure I am using.
Class doing all the operations:
@Component
public class MyClassImpl implements MyClass {
@Autowired
MyOtherClass myOtherClass;
@Override
public void run() {
while (expression) {
// get some data into and entity object
myOtherClass.insertMethod(entity);
myOtherClass.updateMethod(entityId);
}
}
}
my other class:
@Component
public class MyOtherClassImpl implements MyOtherClass {
@Override
JpaClass jpaClass;
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void insertMethod(EntityObject entity) {
jpaClass.save(entity);
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void updateMethod(String entityId) {
EntityObject entity = jpaClass.findById(entityId);
//change something on the entity
jpaClass.save(entity);
}
}
entity object:
public interface JpaClass extends JpaRepository<EntityObject, Long> {
EntityObject findById(String entityId);
}
the problem I am having is that the insert works just fine, but within the while loop I cannot get any updates to work like i have them. I have tried moving the logic around and putting the findById logic in a different method but cannot get it working. I am trying to update 1 row in a table which handles 1 value I then need to reference in the next run of the while loop.
so it goes:
- get value
- operate using value
- update value
- repeat
I set up the database config using spring @Configuration on a class which works fine for all transactions, for reference it is essentially set up like this:
@Configuration
@EnableTransactionManagement
@PropertySource(value = { "classpath:/${app.execution.environment}/application.properties" })
@EnableJpaRepositories(basePackages = "com.example", entityManagerFactoryRef = "mysqlEntityManager", transactionManagerRef = "mysqlTransactionManager")
public class MysqlHibernateConfig {
// all the needed beans here
}
Just to confirm as well, i ran this logic without the while loop and the data does update as expected, so the problem is somewhere in the database transaction, but I am stuck on how to resolve it.