I am using Spring with jpa with the following configuration:
@Configuration
public class JPAConfiguration
{
protected static final String PERSISTENCE_UNIT_NAME = "persistenceUnit";
@Autowired
private DatabaseConfigurationProperties databaseConfigurationProperties;
@Bean
public JpaTransactionManager createJPATransactionManager(EntityManagerFactory emf)
{
JpaTransactionManager jtManager = new JpaTransactionManager();
jtManager.setPersistenceUnitName(PERSISTENCE_UNIT_NAME);
jtManager.setEntityManagerFactory(emf);
return jtManager;
}
@Bean
public LocalContainerEntityManagerFactoryBean createEntityManagerFactoryBean(DataSource dataSource)
{
LocalContainerEntityManagerFactoryBean lcemfb = new LocalContainerEntityManagerFactoryBean();
lcemfb.setDataSource(dataSource);
lcemfb.setPersistenceUnitName(PERSISTENCE_UNIT_NAME);
lcemfb.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
lcemfb.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return lcemfb;
}
@Bean
public DataSource getDataSource()
{
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(databaseConfigurationProperties.getDriver());
dataSource.setUrl(databaseConfigurationProperties.getUrl());
dataSource.setUsername(databaseConfigurationProperties.getUser());
dataSource.setPassword(databaseConfigurationProperties.getPassword());
return dataSource;
}
}
I have a DAO which injects the entitymanager as follow:
@PersistenceContext(unitName = "persistenceUnit")
protected EntityManager entityManager;
Somehow, when I use this DAO in threads, the data of the entitymanager is not synchronized. In Thread A i persist an Entity. After that I try to read it in Thread B and it is not present (even when I du a flush on Thread A). For the transaction handling I use the spring @Transactional annotation.
What is the correct way to get spring jpa with hibternate thread safe? I read alot of tutorials, but they all kinda use the same code as me.
thanks alot.