简体   繁体   English

Mongodb 的 Spring Boot 和数据库默认数据

[英]Spring Boot and Database default data with Mongodb

I have a Spring Boot project that use Mongodb.我有一个使用 Mongodb 的 Spring Boot 项目。 So, in my pom i have that dependence:所以,在我的 pom 中,我有这种依赖:

<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.我需要在 Mongodb 数据库中初始化我的数据,例如使用默认角色。 What is the best way in Spring Boot framework? Spring Boot 框架中最好的方法是什么?

There are several ways to do this, I will suggest you with CommandlineRunner有几种方法可以做到这一点,我会建议你使用CommandlineRunner

try:尝试:

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

}

Otherwise you can use @PostConstruct to initiate it..否则你可以使用@PostConstruct来启动它..

if you need something like liquibase for RDBMS, checkout mongobee: https://github.com/mongobee/mongobee如果您需要 RDBMS 的liquibase类的东西,请查看 mongobee: https ://github.com/mongobee/mongobee

As @Jaiwo99 say i understand that there is not a standard for do that.正如@Jaiwo99 所说,我知道没有标准可以做到这一点。 So i decided to make the work with Spring Batch.所以我决定使用 Spring Batch 来完成这项工作。 I realized a batch for load from CSV files Roles and Permissions of my application.我实现了从我的应用程序的 CSV 文件角色和权限加载的批处理。

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

At least, there is one more way how to initialize data in Mongodb using Spring Boot.至少,还有一种方法可以使用 Spring Boot 在 Mongodb 中初始化数据。 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.当然,您必须检查集合是否不存在,以便在数据库已经创建的情况下不创建集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM