这是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安全性设置了基本身份验证,但是在测试任何端点时我仍然会遭到未经授权,所以我想这是因为启动应用程序时未填充users表,所以我然后通过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;
}
}
答案 0 :(得分:0)
尽管您没有向我们展示所有相关代码,但我想问题出在您的项目结构以及如何创建实体和存储库。
要在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