I want to add some entity data into db on startup of spring boot application. I'm using spring data jpa repositories to save data to the db. I've tried using @PostConstruct annotation to a method and ApplicationListener interface, etc. but no success at all. Code is executed in both case but it doesn't write any data to db. How can I achieve it?
Code :
@Component
public class DatabaseFillerOnStartup implements ApplicationListener {
@Autowired
private UserRepository userRepository;
private static Logger logger = LoggerFactory.getLogger(DatabaseFillerOnStartup.class);
@Override
public void onApplicationEvent(ApplicationEvent event) {
logger.info("===================================" +event.toString());
User user = new User("test");
user.setFirstName("test");
user.setLastName("test");
user.setEmail("[email protected]");
user.setContactNumber("1234567890");
userRepository.save(user);
}
}
Configuration :
@Configuration
@EnableTransactionManagement
@ComponentScan("com.furniturepool.bll.config" )
@PropertySource(value = "classpath:application.properties" )
public class HibernateConfiguration {
@Autowired
private Environment environment;
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan("domain.package" );
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(environment.getRequiredProperty("spring.datasource.url"));
dataSource.setUsername(environment.getRequiredProperty("spring.datasource.username"));
dataSource.setPassword(environment.getRequiredProperty("spring.datasource.password"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
Repository :
interface UserRepository extends CrudRepository<User, Long> {
}