【问题标题】:Spring boot multiple database not creating tablesSpring引导多个数据库不创建表
【发布时间】:2019-06-20 15:35:01
【问题描述】:

这是 application.properties 文件中数据库的定义: 第一个数据库:

spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/police_db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=Admin
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver

第二个数据库配置:

enroll.datasource.jdbc-url=jdbc:mysql://localhost:3306/enrollment_db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
enroll.datasource.username=root
enroll.datasource.password=Admin
enroll.datasource.driverClassName=com.mysql.cj.jdbc.Driver

我为两个数据库创建了两个配置类,这是第一个或主数据库的配置类:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory",
        basePackages = {"com.cpm.repository"})
public class PoliceDbConfig {

    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            EntityManagerFactoryBuilder builder, @Qualifier("dataSource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("com.cpm.model").persistenceUnit("model")
                .build();
    }


    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

这是第二个数据库的配置类:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "barEntityManagerFactory",
        transactionManagerRef = "barTransactionManager", basePackages = {"com.enrollment.repository"})
public class EnrollmentDbConfig {

    @Bean(name = "enrollmentDatasource")
    @ConfigurationProperties(prefix = "enroll.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "barEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean barEntityManagerFactory(
            EntityManagerFactoryBuilder builder, @Qualifier("enrollmentDatasource") DataSource dataSource) {
        return builder.dataSource(dataSource).
                packages("com.enrollment.model").
                persistenceUnit("model")
                .build();
    }

    @Bean(name = "barTransactionManager")
    public PlatformTransactionManager barTransactionManager(
            @Qualifier("barEntityManagerFactory") EntityManagerFactory barEntityManagerFactory) {
        return new JpaTransactionManager(barEntityManagerFactory);
    }
}

我遇到的主要问题是实体的表不是自动生成的,我在网络上搜索了这个问题,并被告知要添加此注释:

spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create

第一个注释创建表,但如果我删除它并只留下我需要的第二个注释,则不会创建表。

另一个问题是我在资源文件夹中有一个 sql 脚本,它应该在应用程序启动时运行并填充表,但它没有这样做。

最后一个问题是,我使用 spring security 设置了基本身份验证,但是当我测试我的任何端点时仍然未经授权,所以我猜这是因为应用程序启动时未填充用户表,所以我然后通过 MYSQL 工作台手动添加用户并尝试端点,但仍然导致未经授权的错误。

对于这些问题的任何帮助将不胜感激。 更新: 这是安全配置类:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final SystemUserDetailService userDetailsService;

    @Autowired
    public SecurityConfig(SystemUserDetailService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //.antMatchers("/verification/**","/admin/**", "/login/**","/logout/**").authenticated()
                .antMatchers("/verification/**","/admin/**", "/login/**","/logout/**").authenticated()
                .and()
                .httpBasic()
                .realmName("Bio Connect")
                .and()
                .csrf()
                .disable();
    }
}

另外,这是我的 UserDetailService 类:

@Component
public class SystemUserDetailService implements UserDetailsService {

    private final SystemUserRepository repository;

    @Autowired
    public SystemUserDetailService(SystemUserRepository repository) {
        this.repository = repository;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SystemUser user = repository.findByUsername(s);
        if(user == null) {
            throw new UsernameNotFoundException(String.format("User with the username %s doesn't exist", s));
        }

        // Create a granted authority based on user's role.
        // Can't pass null authorities to user. Hence initialize with an empty arraylist
        List<GrantedAuthority> authorities = new ArrayList<>();
        if(user.isAdmin()) {
            authorities = AuthorityUtils.createAuthorityList("ROLE_ADMIN");
        }
        // Create a UserDetails object from the data
        UserDetails userDetails = new User(user.getUsername(), user.getPassword(), authorities);

        return userDetails;
    }
}

【问题讨论】:

  • 能否也添加您的 Spring Security 配置?
  • 在一篇文章中提出多个大问题是不行的,如果问题和答案同时包含您的 Spring Data JPA 和 Spring 安全问题,那么这些帖子将很长,因此您的安全相关问题创建另一个帖子
  • 一次只关注一个问题,以便从 stackians 中获得最大收益!单独创建问题以增加反馈和解决方案。
  • 我已经为安全配置添加了类,

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


【解决方案1】:

虽然您没有向我们展示所有相关代码,但我想问题在于您的项目结构以及您如何创建实体和存储库。

要使用 spring 使用两个单独的数据库,我更喜欢为两个数据库的实体提供两个单独的包,您还需要为两个数据库分别提供 Repositories

src/main/java
- com.multipledb   //Your db config classes are located here
  - firstdb
    - model  //entities of first database are located here
    - dao    //repositories of first database are located here
  - seconddb
    - model  //entities of second database are located here
    - dao    //repositories of second database are located here

【讨论】:

  • 我使用相同的结构,但是在我的模型文件夹中,还有另一个包含模型的嵌套文件夹,这会是一个问题
猜你喜欢
  • 2017-09-02
  • 1970-01-01
  • 2023-02-10
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
相关资源
最近更新 更多