使用spring数据jpa在启动时将数据保存到db

时间:2016-06-28 17:29:31

标签: java spring spring-mvc spring-boot spring-data-jpa

我想在启动spring boot应用程序时将一些实体数据添加到db中。我使用spring数据jpa存储库将数据保存到db。我已尝试将@PostConstruct注释用于方法和ApplicationListener界面等,但根本没有成功。代码在两种情况下都会执行,但它不会将任何数据写入db。我怎样才能实现它?

代码:

@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("test@test.com");
        user.setContactNumber("1234567890");
        userRepository.save(user);
    }

}

配置:

@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;
    }
}

存储库:

interface UserRepository extends CrudRepository<User, Long> {
}

2 个答案:

答案 0 :(得分:2)

在没有任何其他配置的情况下,我将一个使用H2数据库作为存储的示例应用程序和一个用于存储和检索用户的JpaRepository放在一起。

spring-data-jpa-repository-example

只需运行我已添加的测试。

Mysql DB的配置示例:

{
        "country": "France",
        "customerId": "France001",
        "visited": [
            {
                "placeName": "US",
                "rating": "2.3",
                "famousRest": "N/A",
                "placeId": "AVBS34"

            },
              {
                "placeName": "US",
                "rating": "3.3",
                "famousRest": "SeriousPie",
                "placeId": "VBSs34"

            },
              {
                "placeName": "Canada",
                "rating": "4.3",
                "famousRest": "TimHortons",
                "placeId": "AVBv4d"

            }        
    ]
}

请记住将MySQL添加到类路径中。

希望这有帮助。

贾斯汀

答案 1 :(得分:0)

确保您已提交交易了吗? 或者在这里放置'userrepository'代码和spring-data-jpa xml配置。