dimanche 29 mars 2015

JPA Populate Data on App Start

I am working on developing a mechanism to load data into the database on boot for JPA. We are using the code first approach with JPA/Hibernate, so hibernate is actually generating the schema every time the applications starts. The kicker is I only want this to happen when the active profile is "dev" however I think I'm on the right track there. I have seen suggestions of using a bean to do this but I think I'm not quite getting it.


This is the code I has so far.



@Configuration
@Profile("dev")
public class DataInitializer {

@Autowired
UserService userService;

@Autowired
UserRepository userRepository;

@Autowired
PasswordEncoder passwordEncoder;

@Bean
public DataInitializer dataInitializer() {

User user = userRepository.findByUserName("admin");
if (user == null) {
User newUser = new User();
newUser.setUserName("admin");
newUser.setEmail("admin@app.com");
newUser.setFirstName("Application");
newUser.setLastName("Admin");
newUser.setPassword(passwordEncoder.encode("password"));
userRepository.save(newUser);
}
}
}

Aucun commentaire:

Enregistrer un commentaire