2

I have a Spring Boot project that use Mongodb. So, in my pom i have that dependence:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

So i'm able to access to the database with this repository class:

package it.de.marini.server.dal;

import org.springframework.data.mongodb.repository.MongoRepository;

import it.de.marini.server.model.Role;

public interface RoleRepository extends MongoRepository<Role, String> {

}

I need to inizialize my data in Mongodb database putting default Role for example. What is the best way in Spring Boot framework?

3 Answers 3

3

There are several ways to do this, I will suggest you with CommandlineRunner

try:

@Bean
public CommandLineRunner initConfig(MyRepo repo) {
  if (data not exist) {
      repo.save(...);
  }

}

Otherwise you can use @PostConstruct to initiate it..

if you need something like liquibase for RDBMS, checkout mongobee: https://github.com/mongobee/mongobee

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

Comments

0

As @Jaiwo99 say i understand that there is not a standard for do that. So i decided to make the work with Spring Batch. I realized a batch for load from CSV files Roles and Permissions of my application.

@Configuration
@EnableBatchProcessing
public class BatchConfiguration {

@Autowired
public JobBuilderFactory jobBuilderFactory;

@Autowired
public StepBuilderFactory stepBuilderFactory;

@Autowired
public MongoTemplate mongoTemplate;

@Bean
public PlatformTransactionManager transactionManager() {
    return new ResourcelessTransactionManager();
}

@Bean
public Tasklet defaultRolePermissionTasklet() {
    return new DefaultRolePermissionTasklet();
}


public <T> FlatFileItemReader<T> readerFile(String fileName,String[] fields,Class<T> type)  {

    FlatFileItemReader<T> reader = new FlatFileItemReader<T>();
    reader.setStrict(false);
    reader.setResource(new ClassPathResource(fileName));
    reader.setLineMapper(new DefaultLineMapper<T>() {
        {
            setLineTokenizer(new DelimitedLineTokenizer() {
                {
                    setNames(fields);
                    setStrict(false);
                }
            });
            setFieldSetMapper(new BeanWrapperFieldSetMapper<T>() {
                {
                    setTargetType(type);
                }
            });
        }
    });
    return reader;

}

@Bean
public PermissionItemProcessor permissionProcessor() {
    return new PermissionItemProcessor();
}

@Bean
public RoleItemProcessor roleProcessor() {
    return new RoleItemProcessor();
}

@Bean
public Job initAuthenticationData(JobCompletionNotificationListener listener) {
    return jobBuilderFactory.get("initAuthenticationData").incrementer(new RunIdIncrementer()).listener(listener)
            .start(stepPermission())
            .next(stepRole())
            .next(stepDefaultRolePermissions())
            .build();
}

@Bean
public Step stepDefaultRolePermissions() {
    return stepBuilderFactory.get("stepDefaultRolePermissions").tasklet(defaultRolePermissionTasklet()).build();
}


@Bean
public Step stepPermission() {

    MongoItemWriter<Permission> writer = new MongoItemWriter<Permission>();
    writer.setTemplate(mongoTemplate);




    return stepBuilderFactory.get("stepPermission").<Permission, Permission>chunk(20)
            .reader(readerFile("permission-data.csv",new String[] {"name","description"},Permission.class))
            .processor(permissionProcessor())
            .writer(writer)
            .build();
}

@Bean
public Step stepRole() {
    MongoItemWriter<Role> writer = new MongoItemWriter<Role>();
    writer.setTemplate(mongoTemplate);

    return stepBuilderFactory.get("stepRole").<Role, Role>chunk(20)
            .reader(readerFile("role-data.csv",new String[] {"name","description"},Role.class))
            .processor(roleProcessor())
            .writer(writer)
            .build();
    }
}

Comments

0

At least, there is one more way how to initialize data in Mongodb using Spring Boot. You can create in your configuration like this:

@Configuration
public class AppConfiguration {

    @Autowired
    public void prepare(ReactiveMongoOperations mongoOperations,
                        UserRepository userRepository) {
        mongoOperations.createCollection("users",
                CollectionOptions.empty()
                        .maxDocuments(1_000)
                        .size(1024 * 8)
                        .capped()).block();
        userRepository
                .insert(List.of(
                        User.builder()
                                .name("Joe Doe")
                                .build()
                ))
                .blockLast();
    }
}

And of course, you must make a check that collection doesn't exist, in order to not create a collection if the database has already been created.

Comments

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.