#sql-server #hibernate #spring-boot #spring-data-jpa #spring-data
#sql-server #переход в спящий режим #весенняя загрузка #spring-data-jpa #весна-данные
Вопрос:
Я пытаюсь подключиться к разным источникам данных с помощью Spring Boot и Spring Data JPA. Я использую spring boot 2.1.3.RELEASE. Я использовал следующее в качестве ссылки https://github.com/sivaprasadreddy/beginning-spring-boot-2/tree/master/chapter-08/springboot-multiple-datasources-demo Вот код, который я использую
DBAppConfig.java #(Первое подключение к источнику данных)
package com.bmi.config;
@Configuration
@EnableJpaRepositories(
basePackages = "com.bmi.app.repository",
entityManagerFactoryRef = "appEntityManagerFactory",
transactionManagerRef = "appTransactionManager"
)
public class DBAppConfig {
@Autowired
private Environment env;
@Bean
@ConfigurationProperties(prefix="datasource.app")
public DataSourceProperties securityDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
public DataSource securityDataSource() {
DataSourceProperties securityDataSourceProperties = securityDataSourceProperties();
return DataSourceBuilder.create()
.driverClassName(securityDataSourceProperties.getDriverClassName())
.url(securityDataSourceProperties.getUrl())
.username(securityDataSourceProperties.getUsername())
.password(securityDataSourceProperties.getPassword())
.build();
}
@Bean
public PlatformTransactionManager securityTransactionManager()
{
EntityManagerFactory factory = securityEntityManagerFactory().getObject();
return new JpaTransactionManager(factory);
}
@Bean
public LocalContainerEntityManagerFactoryBean securityEntityManagerFactory()
{
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(securityDataSource());
factory.setPackagesToScan(new String[]{"com.bmi.app.entity"});
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
jpaProperties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql"));
factory.setJpaProperties(jpaProperties);
return factory;
}
}
DBRapportConfig.java #(Второй источник данных)
package com.bmi.config;
@Configuration
@EnableJpaRepositories(
basePackages = "com.bmi.rapport.repository",
entityManagerFactoryRef = "rapportEntityManagerFactory",
transactionManagerRef = "rapportTransactionManager"
)
public class DBRapportConfig {
@Autowired
private Environment env;
@Bean
@ConfigurationProperties(prefix="datasource.rapport")
public DataSourceProperties ordersDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
public DataSource ordersDataSource() {
DataSourceProperties primaryDataSourceProperties = ordersDataSourceProperties();
return DataSourceBuilder.create()
.driverClassName(primaryDataSourceProperties.getDriverClassName())
.url(primaryDataSourceProperties.getUrl())
.username(primaryDataSourceProperties.getUsername())
.password(primaryDataSourceProperties.getPassword())
.build();
}
@Bean
public PlatformTransactionManager ordersTransactionManager()
{
EntityManagerFactory factory = ordersEntityManagerFactory().getObject();
return new JpaTransactionManager(factory);
}
@Bean
public LocalContainerEntityManagerFactoryBean ordersEntityManagerFactory()
{
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(ordersDataSource());
factory.setPackagesToScan(new String[]{"com.bmi.rapport.entity"});
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
jpaProperties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql"));
factory.setJpaProperties(jpaProperties);
return factory;
}
}
WebMvcConfig.java
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter
{ @Bean
public OpenEntityManagerInViewFilter securityOpenEntityManagerInViewFilter()
{
OpenEntityManagerInViewFilter osivFilter = new OpenEntityManagerInViewFilter();
osivFilter.setEntityManagerFactoryBeanName("appEntityManagerFactory");
return osivFilter;
}
@Bean
public OpenEntityManagerInViewFilter ordersOpenEntityManagerInViewFilter()
{
OpenEntityManagerInViewFilter osivFilter = new OpenEntityManagerInViewFilter();
osivFilter.setEntityManagerFactoryBeanName("rapportEntityManagerFactory");
return osivFilter;
}}
UtilisateurDetailsService # (where the error says)
package com.bmi.service.app;
@Service
public class UtilisateurDetailsService implements UserDetailsService{
@Autowired
private UtilisateurRepository utilisateurRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Utilisateur utilisateur=utilisateurRepository.findByUtilisateurEmail(email);
if(utilisateur==null)
throw new UsernameNotFoundException("utilisateur n'exist pas ");
return new UtilisateurDetails(utilisateur);
}
}
application.properties
datasource.app.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
datasource.app.url=jdbc:sqlserver://pfe2019.hopto.org;databaseName=BMI_APP_DB
datasource.app.username=sa
datasource.app.password=Admin123
datasource.rapport.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
datasource.rapport.url=jdbc:sqlserver://pfe2019.hopto.org;databaseName=MAINTA_TEST
datasource.rapport.username=sa
datasource.rapport.password=Admin123
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
pom.xml #
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.bmi</groupId>
<artifactId>BmiReport</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>BmiReport</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.5.1</version>
</dependency>
</dependencies>
Во время запуска выдается следующая ошибка:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field utilisateurRepository in com.bmi.service.app.UtilisateurDetailsService required a bean named 'appEntityManagerFactory' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean named 'appEntityManagerFactory' in your configuration.
Заранее благодарю вас за помощь.
Комментарии:
1. Взгляните на официальную документацию docs.spring.io/spring-boot/docs/current/reference/html /…
2. привет, спасибо @SimonMartinelli я видел эту документацию до того, как исправил ошибку, но теперь я получил эту ошибку #»не удалось выполнить инструкцию; SQL [n / a]; вложенным исключением является org.hibernate.exception. Исключение SQLGrammarException: не удалось выполнить инструкцию»#
3. Не могли бы вы, пожалуйста, опубликовать весь stacktrace в вопросе?
4. @SimonMartinelli я все равно решил свою проблему, спасибо за ваш ответ!