2

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> {
}
6
  • I've found with Hibernate that the best thing to do is to set the log level as high as possible (although DEBUG will most likely do it) and to study the output thoroughly. There's quite often and error in the logs or at least a hint as to what to try next. Commented Jun 28, 2016 at 18:15
  • @JLove : let me check with debug mode Commented Jun 29, 2016 at 3:28
  • @JLove : I can read data from db... but saving not working .... it's just returning the object itself , without throwing any kind of error Commented Jun 29, 2016 at 4:44
  • Can you please post your repository code as well as your Hibernate configuration code. Commented Jun 30, 2016 at 7:58
  • @JLove : ok i will post after few minutes Commented Jun 30, 2016 at 7:59

2 Answers 2

2

Without any of the rest of your config, I've put together a sample application which uses a H2 database as storage, and a JpaRepository to store and retrieve a User.

spring-data-jpa-repository-example

Just run the test I've added.

Example config for Mysql DB:

spring:
  jpa:
    show-sql: true
    hibernate:
      naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
      dialect: org.hibernate.dialect.MySQL5Dialect
      ddl-auto: create-drop
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/testdb?createDatabaseIfNotExist=true
    test-on-borrow: true
    validation-query: SELECT 1
    username: xxx
    password: xxx

Remember to add MySQL to your classpath.

Hope this helps.

Justin

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your help :) , but can I create the data to production machine using test code?
@PranavCBalan This is production ready code, I've just created it as a Junit test so that I don't need to setup the rest of the application. Please note my comment above regarding datasources also mark as the answer if it resolves you issue.
I need to write that data to the production server
@PranavCBalan: Ok, so in application.yaml swap the configuration of the H2 in-memory database for a disk based database. I think this is a separate issue from whether you can store and retrieve correctly from the repository.
I've ammended my answer to include the config which can be used for a MySQL db.
|
0

make sure you have commit the transaction yet? or put your 'userrepository' code and spring-data-jpa xml configuration here.

1 Comment

The life-cycle of the entities are handled by the repository, without explicitly defining a transaction, the boundary for the transaction will be each method call on the repository. You shouldn't need to commit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.