Issue
I have this CommandLineRunner in my Main class (ReservationprojectApplication)
@Bean
CommandLineRunner run(UserService userService) {
return args -> {
userService.saveRole(new Role(null, "ROLE_ADMIN"));
userService.saveRole(new Role(null, "ROLE_STUDENT"));
userService.saveUser(new User("administrator", "[email protected]", "t", new ArrayList<>(), Instant.now(), true));
userService.saveUser(new User("elias", "[email protected]", "t", new ArrayList<>(), Instant.now(), true));
userService.addRoleToUser("administrator", "ROLE_ADMIN");
userService.addRoleToUser("elias", "ROLE_STUDENT");
};
}
Is there a way to only run this code once the ddl-auto is set to create? I don't want to comment this code each time my ddl-auto is set to update.
spring:
# Database properties
datasource:
password: blabla
url: jdbc:postgresql://localhost:5432/cegeka_reservation
username: postgres
jpa:
hibernate:
**ddl-auto: update**
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
format_sql: true
show_sql: true
Thanks in advance!
Solution
You should have access to the property so it is easy enough to check it
@Value("${spring.jpa.hibernate.ddl-auto}")
private String ddl;
@Bean
CommandLineRunner run(UserService userService) {
if ("create".equals(ddl) {
// Rest of your code here
}
}
Answered By - grekier
Answer Checked By - Katrina (JavaFixing Volunteer)