问:
How to fix, 'class path resource [...] cannot be opened because it doesn't exist' at runtime with Spring
When trying to implement a simple websocket implementation into our Springboot application I keep running into an error, apologies as I have to obfuscate some of the non-problem related information.

```<code>Failed to load bean class: com.######.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
</code>```

The problem happens at runtime when I try to deploy to debug and test but not during the Maven build.

I have tried multiple example on the web for implementing websockets with Spring and JS/React using Stomp, SockJS and I always come up with some form of this same error message, where SwaggerConfig has a nested FileNotFoundException due to some class I need to create the websocket connection on my server side. Be aware that I am limited to Spring version 4.0.9.RELEASE due to wider project dependencies so I can't use anything requiring newer deps.

My following code uses the bare minimum example found at,
https://www.javainuse.com/spring/boot-websocket

My handler class:

```<code>import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class SocketTextHandler extends TextWebSocketHandler {

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException, JSONException {

        String payload = message.getPayload();
        JSONObject jsonObject = new JSONObject(payload);
        session.sendMessage(new TextMessage("Hi " + jsonObject.get("user") + " how may we help you?"));
    }

}
</code>```

My websocket-config class:

```<code>import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new SocketTextHandler(), "/user");
    }

}
</code>```

My Pom.xml includes the following dependencies:

```<code><properties>
    <spring.version>4.0.9.RELEASE</spring.version>
</properties>
...
<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
        <type>jar</type>
        <scope>compile</scope>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
        <type>jar</type>
        <scope>compile</scope>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
        <type>jar</type>
        <scope>compile</scope>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <type>jar</type>
        <scope>compile</scope>
      </dependency>
...
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
        <version>1.1.12.RELEASE</version>
</dependency>
</code>```

Finally my React app uses this component to simply display the data when/if it connects:

```<code>const WebSocketStream = () => {
    const [text, setText] = React.useState<string>("Hello!");
    const [connected, setConnected] = React.useState<boolean>(false);
    let ws:WebSocket;

    const connect = () => {
        ws = new WebSocket('ws://localhost:8080/app/user');
        ws.onmessage = (data) => {
            setText(data.data);
        }
        setConnected(true);
    };

    const disconnect = () => {
        if (ws != null) {
            ws.close();
        }
        setConnected(false);
        console.log("Websocket is in disconnected state");
    };

    const sendMessage = () => {
        const data = JSON.stringify({
            'user' : 'I was here'
        });
        ws.send(data);
    }

    return (
        <WebSocketStreamWrapper>
            {text + "\n"}
            {connected ? "Connected!" : "Not connected :("}
            <Button onClick={connect}>Connect</Button>
            <Button onClick={sendMessage}>Send Message</Button>
            <Button onClick={disconnect}>Disconnect</Button>
        </WebSocketStreamWrapper>
    );
};

export default WebSocketStream;
</code>```

I would expect the server to at least get up and running so I can hopefully connect from the front end with a websocket. Here is the full error message,

```<code>16:16:05,380 ERROR [org.springframework.web.context.ContextLoader] (MSC service thread 1-4) Context initialization failed: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:163) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:305) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:611) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) [org.springframework-spring-web-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) [org.springframework-spring-web-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) [org.springframework-spring-web-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:173) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:193) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [rt.jar:1.8.0_202]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [rt.jar:1.8.0_202]
    at java.lang.Thread.run(Thread.java:748) [rt.jar:1.8.0_202]
Caused by: java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172) [com.business.ws-viz-script-common-8.9.1-20190523.213339-28.jar:]
    at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:50) [com.business.ws-viz-script-common-8.9.1-20190523.213339-28.jar:]
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:98) [com.business.ws-viz-script-common-8.9.1-20190523.213339-28.jar:]
    at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102) [com.business.ws-viz-script-common-8.9.1-20190523.213339-28.jar:]
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:93) [com.business.ws-viz-script-common-8.9.1-20190523.213339-28.jar:]
    at org.springframework.context.annotation.ConfigurationClassParser.asSourceClass(ConfigurationClassParser.java:566) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser$SourceClass.getSuperClass(ConfigurationClassParser.java:741) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:285) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:219) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:177) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:253) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:219) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:177) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:159) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    ... 18 more

16:16:05,389 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./app: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./app: Failed to start service
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [rt.jar:1.8.0_202]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [rt.jar:1.8.0_202]
    at java.lang.Thread.run(Thread.java:748) [rt.jar:1.8.0_202]
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:222)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
    ... 3 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:163)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:305)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:611)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:173)
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:193)
    ... 7 more
Caused by: java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
    at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:50)
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:98)
    at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102)
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:93)
    at org.springframework.context.annotation.ConfigurationClassParser.asSourceClass(ConfigurationClassParser.java:566)
    at org.springframework.context.annotation.ConfigurationClassParser$SourceClass.getSuperClass(ConfigurationClassParser.java:741)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:285)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:219)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:177)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:253)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:219)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:177)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:159)
    ... 18 more

16:16:05,399 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 4) JBAS014613: Operation ("deploy") failed - address: ([("deployment" => "app-ear-10.0.0-SNAPSHOT.ear")]) - failure description: {"JBAS014671: Failed services" => {"jboss.undertow.deployment.default-server.default-host./app" => "org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./app: Failed to start service
    Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    Caused by: java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist"}}
16:16:05,401 ERROR [org.jboss.as.server] (management-handler-thread - 4) JBAS015870: Deploy of deployment "app-ear-10.0.0-SNAPSHOT.ear" was rolled back with the following failure message:
{"JBAS014671: Failed services" => {"jboss.undertow.deployment.default-server.default-host./app" => "org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./app: Failed to start service
    Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    Caused by: java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist"}}
</code>```

答: The problem was with the child artifact poms. If anyone else runs across this problem, check that your parent dependencies are also in your child poms, I haven't run a root cause analysis but adding the dependencies to the child poms as well solved the issue.</p>

Body:
When trying to implement a simple websocket implementation into our Springboot application I keep running into an error, apologies as I have to obfuscate some of the non-problem related information.

Failed to load bean class: com.######.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist

The problem happens at runtime when I try to deploy to debug and test but not during the Maven build.

I have tried multiple example on the web for implementing websockets with Spring and JS/React using Stomp, SockJS and I always come up with some form of this same error message, where SwaggerConfig has a nested FileNotFoundException due to some class I need to create the websocket connection on my server side. Be aware that I am limited to Spring version 4.0.9.RELEASE due to wider project dependencies so I can't use anything requiring newer deps.

My following code uses the bare minimum example found at,
https://www.javainuse.com/spring/boot-websocket

My handler class:

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class SocketTextHandler extends TextWebSocketHandler {

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException, JSONException {

        String payload = message.getPayload();
        JSONObject jsonObject = new JSONObject(payload);
        session.sendMessage(new TextMessage("Hi " + jsonObject.get("user") + " how may we help you?"));
    }

}

My websocket-config class:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new SocketTextHandler(), "/user");
    }

}

My Pom.xml includes the following dependencies:

<properties>
    <spring.version>4.0.9.RELEASE</spring.version>
</properties>
...
<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
        <type>jar</type>
        <scope>compile</scope>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
        <type>jar</type>
        <scope>compile</scope>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
        <type>jar</type>
        <scope>compile</scope>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <type>jar</type>
        <scope>compile</scope>
      </dependency>
...
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
        <version>1.1.12.RELEASE</version>
</dependency>

Finally my React app uses this component to simply display the data when/if it connects:

const WebSocketStream = () => {
    const [text, setText] = React.useState<string>("Hello!");
    const [connected, setConnected] = React.useState<boolean>(false);
    let ws:WebSocket;

    const connect = () => {
        ws = new WebSocket('ws://localhost:8080/app/user');
        ws.onmessage = (data) => {
            setText(data.data);
        }
        setConnected(true);
    };

    const disconnect = () => {
        if (ws != null) {
            ws.close();
        }
        setConnected(false);
        console.log("Websocket is in disconnected state");
    };

    const sendMessage = () => {
        const data = JSON.stringify({
            'user' : 'I was here'
        });
        ws.send(data);
    }

    return (
        <WebSocketStreamWrapper>
            {text + "\n"}
            {connected ? "Connected!" : "Not connected :("}
            <Button onClick={connect}>Connect</Button>
            <Button onClick={sendMessage}>Send Message</Button>
            <Button onClick={disconnect}>Disconnect</Button>
        </WebSocketStreamWrapper>
    );
};

export default WebSocketStream;

I would expect the server to at least get up and running so I can hopefully connect from the front end with a websocket. Here is the full error message,

16:16:05,380 ERROR [org.springframework.web.context.ContextLoader] (MSC service thread 1-4) Context initialization failed: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:163) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:305) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:611) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) [org.springframework-spring-web-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) [org.springframework-spring-web-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) [org.springframework-spring-web-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:173) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:193) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [rt.jar:1.8.0_202]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [rt.jar:1.8.0_202]
    at java.lang.Thread.run(Thread.java:748) [rt.jar:1.8.0_202]
Caused by: java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172) [com.business.ws-viz-script-common-8.9.1-20190523.213339-28.jar:]
    at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:50) [com.business.ws-viz-script-common-8.9.1-20190523.213339-28.jar:]
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:98) [com.business.ws-viz-script-common-8.9.1-20190523.213339-28.jar:]
    at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102) [com.business.ws-viz-script-common-8.9.1-20190523.213339-28.jar:]
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:93) [com.business.ws-viz-script-common-8.9.1-20190523.213339-28.jar:]
    at org.springframework.context.annotation.ConfigurationClassParser.asSourceClass(ConfigurationClassParser.java:566) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser$SourceClass.getSuperClass(ConfigurationClassParser.java:741) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:285) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:219) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:177) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:253) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:219) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:177) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:159) [org.springframework-spring-context-4.0.9.RELEASE.jar:4.0.9.RELEASE]
    ... 18 more

16:16:05,389 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./app: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./app: Failed to start service
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [rt.jar:1.8.0_202]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [rt.jar:1.8.0_202]
    at java.lang.Thread.run(Thread.java:748) [rt.jar:1.8.0_202]
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:222)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
    ... 3 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:163)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:305)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:254)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:94)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:611)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:173)
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:193)
    ... 7 more
Caused by: java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
    at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:50)
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:98)
    at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102)
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:93)
    at org.springframework.context.annotation.ConfigurationClassParser.asSourceClass(ConfigurationClassParser.java:566)
    at org.springframework.context.annotation.ConfigurationClassParser$SourceClass.getSuperClass(ConfigurationClassParser.java:741)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:285)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:219)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:177)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:253)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:219)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:177)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:159)
    ... 18 more

16:16:05,399 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 4) JBAS014613: Operation ("deploy") failed - address: ([("deployment" => "app-ear-10.0.0-SNAPSHOT.ear")]) - failure description: {"JBAS014671: Failed services" => {"jboss.undertow.deployment.default-server.default-host./app" => "org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./app: Failed to start service
    Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    Caused by: java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist"}}
16:16:05,401 ERROR [org.jboss.as.server] (management-handler-thread - 4) JBAS015870: Deploy of deployment "app-ear-10.0.0-SNAPSHOT.ear" was rolled back with the following failure message:
{"JBAS014671: Failed services" => {"jboss.undertow.deployment.default-server.default-host./app" => "org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./app: Failed to start service
    Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to load bean class: com.business.swagger.SwaggerConfig; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist
    Caused by: java.io.FileNotFoundException: class path resource [org/springframework/web/socket/handler/TextWebSocketHandler.class] cannot be opened because it does not exist"}}


来源: stackexchange

问:
Error creating bean with name 'entityManagerFactory' when trying to access two databases in Spring Boot
I want to create two connections to MySQL databases to work with them and retrive data. I have the connections in my application.properties like this:

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/world?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

bar.datasource.url=jdbc:mysql://localhost:3306/sakila?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
bar.datasource.username=root
bar.datasource.password=root
bar.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.database=default
</code>```

I have created two configuration files for each of the databases I want to connect. The first one is SakilaDbConfig:

```<code>package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;

import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        basePackages = { "com.example.demo.sakila.repo" }
)
public class SakilaDbConfig {

    @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.example.demo.sakila..domain")
                .persistenceUnit("foo")
                .build();
    }

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("entityManagerFactory") EntityManagerFactory
                    entityManagerFactory
    ) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}
enter code here
</code>```

And the second configuration is WorldDbConfig:

```<code>package com.example.demo;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "barEntityManagerFactory",
        transactionManagerRef = "barTransactionManager",
        basePackages = { "com.example.demo.world.repo" }
)
public class WorldDbConfig {

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

    @Bean(name = "barEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    barEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("barDataSource") DataSource dataSource
    ) {
        return
                builder
                        .dataSource(dataSource)
                        .packages("com.example.demo.world.domain")
                        .persistenceUnit("bar")
                        .build();
    }
    @Bean(name = "barTransactionManager")
    public PlatformTransactionManager barTransactionManager(
            @Qualifier("barEntityManagerFactory") EntityManagerFactory
                    barEntityManagerFactory
    ) {
        return new JpaTransactionManager(barEntityManagerFactory);
    }
}
</code>```

But when I try to run the code, it throws me the next error:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/example/demo/SakilaDbConfig.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at com.example.demo.DatabasesApplication.main(DatabasesApplication.java:10) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.5.RELEASE.jar:2.1.5.RELEASE]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:179) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:119) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 21 common frames omitted
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    ... 38 common frames omitted
</code>```

I have read that adding a dependencie fixed the error, but I had added the dependency and still not work. Here is my pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>databases</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-data-jpa</artifactId>
        </dependency>
        <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>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Inside com.example.demo package I have two folders, one for the sakila database and other for the world database, inside each folder there are two other folders, repo and domain. Repo contains the repositories of the databases, and domain the entities. I have read a lot of post but I can not do it work. How can I solve this?

答:
Try adding the hibernate.dialect property

```<code>@Bean(name = "barEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    barEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("barDataSource") DataSource dataSource
    ) {

        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");

        return
                builder
                        .dataSource(dataSource)
                        .packages("com.example.demo.world.domain")
                        .persistenceUnit("bar")
                        //
                        .properties(props)
                        .build();
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to create two connections to MySQL databases to work with them and retrive data. I have the connections in my application.properties like this:

spring.datasource.url=jdbc:mysql://localhost:3306/world?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

bar.datasource.url=jdbc:mysql://localhost:3306/sakila?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
bar.datasource.username=root
bar.datasource.password=root
bar.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.database=default

I have created two configuration files for each of the databases I want to connect. The first one is SakilaDbConfig:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;

import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        basePackages = { "com.example.demo.sakila.repo" }
)
public class SakilaDbConfig {

    @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.example.demo.sakila..domain")
                .persistenceUnit("foo")
                .build();
    }

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

And the second configuration is WorldDbConfig:

package com.example.demo;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "barEntityManagerFactory",
        transactionManagerRef = "barTransactionManager",
        basePackages = { "com.example.demo.world.repo" }
)
public class WorldDbConfig {

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

    @Bean(name = "barEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    barEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("barDataSource") DataSource dataSource
    ) {
        return
                builder
                        .dataSource(dataSource)
                        .packages("com.example.demo.world.domain")
                        .persistenceUnit("bar")
                        .build();
    }
    @Bean(name = "barTransactionManager")
    public PlatformTransactionManager barTransactionManager(
            @Qualifier("barEntityManagerFactory") EntityManagerFactory
                    barEntityManagerFactory
    ) {
        return new JpaTransactionManager(barEntityManagerFactory);
    }
}

But when I try to run the code, it throws me the next error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/example/demo/SakilaDbConfig.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
    at com.example.demo.DatabasesApplication.main(DatabasesApplication.java:10) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.5.RELEASE.jar:2.1.5.RELEASE]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:179) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:119) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 21 common frames omitted
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    ... 38 common frames omitted

I have read that adding a dependencie fixed the error, but I had added the dependency and still not work. Here is my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>databases</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-data-jpa</artifactId>
        </dependency>
        <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>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Inside com.example.demo package I have two folders, one for the sakila database and other for the world database, inside each folder there are two other folders, repo and domain. Repo contains the repositories of the databases, and domain the entities. I have read a lot of post but I can not do it work. How can I solve this?

Body:
Try adding the hibernate.dialect property

@Bean(name = "barEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean
    barEntityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("barDataSource") DataSource dataSource
    ) {

        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");

        return
                builder
                        .dataSource(dataSource)
                        .packages("com.example.demo.world.domain")
                        .persistenceUnit("bar")
                        //
                        .properties(props)
                        .build();
    }


问:
How to remove headers revealing system info when sending mail in php
I am using PHPs mail() function. I've noticed when going through the message (that gets sent) properties that some headers are present which specify

the filename which sent the email

which version of php I'm running

my OS info

I've removed the domain, but this is basically what's included. How can I stop this being included, or am I just being security paranoid? Also, I would like to keep using phps mail function as opposed to setting up something else. Thanks.

```<code>X-PHP-Originating-Script: 1000:emailtest.php
From: hidden@hidden.hh
Reply-To: hidden@hidden.hh
X-Mailer: PHP/5.3.10-1ubuntu3.10
Message-Id: <20140315193810.ADD43120489@hidden.hh>
</code>```

答:
Apart from settings described in this answer
this issue on GitHub suggest removing X-Mailer header like this</p>

```<code>$mail = new PHPMailer(true);
$mail->XMailer = ' ';
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using PHPs mail() function. I've noticed when going through the message (that gets sent) properties that some headers are present which specify

the filename which sent the email

which version of php I'm running

my OS info

I've removed the domain, but this is basically what's included. How can I stop this being included, or am I just being security paranoid? Also, I would like to keep using phps mail function as opposed to setting up something else. Thanks.

X-PHP-Originating-Script: 1000:emailtest.php
From: hidden@hidden.hh
Reply-To: hidden@hidden.hh
X-Mailer: PHP/5.3.10-1ubuntu3.10
Message-Id: <20140315193810.ADD43120489@hidden.hh>

Body:
Apart from settings described in this answer
this issue on GitHub suggest removing X-Mailer header like this

$mail = new PHPMailer(true);
$mail->XMailer = ' ';


问:
How to handle user's upload image or video from a WKWebView?
In my iOS app I have a WKWebView that loads my website.

In my website there is a HTML form that allows users to upload images.

I want to receive when user click on this form attach button so I can request permission for Camera and Photo Library. If user rejects the access I want to dismiss the click.

If user did not select an image from photo library and clicked cancel. The WKWebView reloads my page. I do not want it to reload my page.

```<code>@IBOutlet weak var webView: WKWebView!
webView.navigationDelegate = self
webView.uiDelegate = self
</code>```

Which delegate functions are suitable to my case.

答:
You might want to look into injecting a JS callback for the button's onclick event into the WKWebView with WKUserScript.

You can find a similar question and a great answer on how to do that here.

Body:
In my iOS app I have a WKWebView that loads my website.

In my website there is a HTML form that allows users to upload images.

I want to receive when user click on this form attach button so I can request permission for Camera and Photo Library. If user rejects the access I want to dismiss the click.

If user did not select an image from photo library and clicked cancel. The WKWebView reloads my page. I do not want it to reload my page.

@IBOutlet weak var webView: WKWebView!
webView.navigationDelegate = self
webView.uiDelegate = self

Which delegate functions are suitable to my case.


问:
How to display information on rollover image like facebook people taging
I wonder if anyone can post a code example on how I can display some information when I hover a certain pixel cordinate on an image (just like when I hover a picture on a facebook image and it displays a text of who that person is that I currently have my mouse pointer over).

The diffrence between facebook and my solution is that my picture is not a picture which contains people, but multiple graphs on same picture, so alot of image pixelcordinates is going to display some data when I hover over them.

I also want my sollution to be webbased, and if possible only contain javascript, jquery css html.

Thanks so much in advance =)

答:
ike @jimy says, use an image map. – Alex Thomas 6 mins ago

But to answer your question "...wonder if anyone can post a code example..." i've done this:

HTML

```<code><img name="n00000001" src="http://ajthomas.co.uk/shapes.png" width="300" height="300" border="0" id="n00000001" usemap="#m_00000001" alt="" /><map name="m_00000001" id="m_00000001">

<area shape="rect" coords="28,179,116,256" href="#" title="square" alt="square" />

<area shape="circle" coords="228,66, 45" href="#" title="round" alt="round" />

<area shape="poly" coords="60,32,22,72,51,120,104,109,111,54,60,32" href="#" title="Poly" alt="Poly" />
</code>```

I've put it on jsfiddle for you too - http://jsfiddle.net/ajthomascouk/xsrzz/

I used fireworks, but i'm sure there is free tools out there too.

Hope this helps.

Update

i'm sure there is free tools out there
  too.

Yup, Gimp can do it using this plugin

Good luck...

Body:
ike @jimy says, use an image map. – Alex Thomas 6 mins ago

But to answer your question "...wonder if anyone can post a code example..." i've done this:

HTML

<img name="n00000001" src="http://ajthomas.co.uk/shapes.png" width="300" height="300" border="0" id="n00000001" usemap="#m_00000001" alt="" /><map name="m_00000001" id="m_00000001">

<area shape="rect" coords="28,179,116,256" href="#" title="square" alt="square" />

<area shape="circle" coords="228,66, 45" href="#" title="round" alt="round" />

<area shape="poly" coords="60,32,22,72,51,120,104,109,111,54,60,32" href="#" title="Poly" alt="Poly" />

I've put it on jsfiddle for you too - http://jsfiddle.net/ajthomascouk/xsrzz/

I used fireworks, but i'm sure there is free tools out there too.

Hope this helps.

Update

i'm sure there is free tools out there
  too.

Yup, Gimp can do it using this plugin

Good luck...


问:
Looping for a specific value from list but only have something to search by
Okay im trying too find the connection too get the right element by loop.

My goal is to find 5627 from list3. But i can only use 168 from variable "a" and use one of the lists in the 3 lists to filter by. The answer is too use the first list becouse it got relation with variable a and list 3.

```<code>a = 168

List_of_3_lists = [[5628,168,5627],[2342,553,3113],[4532, 332,2442]]

list3 = [4322, 5627, 3313]

</code>```

I have tried a lot but maan this should be easy but im failing.

答:
You problem statement is unclear but, if I'm guessing correctly, you want to select the first list in list_of_3_Lists that contains a (168) then find the first intersection of that list with list3.

If that is the case, then you can do it with a list comprehension:

```<code>next( n3 for n3 in list3 for lo3 in List_of_3_lists if a in lo3 and n3 in lo3 )

# 5627
</code>```

Body:
Okay im trying too find the connection too get the right element by loop.

My goal is to find 5627 from list3. But i can only use 168 from variable "a" and use one of the lists in the 3 lists to filter by. The answer is too use the first list becouse it got relation with variable a and list 3.

a = 168

List_of_3_lists = [[5628,168,5627],[2342,553,3113],[4532, 332,2442]]

list3 = [4322, 5627, 3313]

I have tried a lot but maan this should be easy but im failing.

Body:
You problem statement is unclear but, if I'm guessing correctly, you want to select the first list in list_of_3_Lists that contains a (168) then find the first intersection of that list with list3.

If that is the case, then you can do it with a list comprehension:

next( n3 for n3 in list3 for lo3 in List_of_3_lists if a in lo3 and n3 in lo3 )

# 5627


问:
Upper Type bound Polymorphic method Scala
I'm trying out some generic functions in Scala but I seem to be stuck trying to get the following example to work:

I've got the following (simplified) problem. I've got a parent config (which is a trait) and two case classes that inherit from this parent config. They both add one extra argument. Then I further got another Parent trait and 2 subclasses that extend this trait. These subclasses both implement the parents methods, it should have both a get config and a print config function. In my main class I then run a runner function which should first get the config, and subsequently print the config.

What I've tried is: changing the bounds, both in the parent and the children. I've also tried to change the return types. However this does not seem to work.

```<code>
trait ParentConfig{val input : String}

case class ConfigOne(input:String, extraArg:String) extends ParentConfig

case class ConfigTwo(input:String, extraTwo:String) extends ParentConfig

</code>```

```<code>trait inheritanceTester {

  def getConfig[A >: ParentConfig](): A

  def printConfig[A <: ParentConfig](conf: A): Unit
}

class ExtensionOne extends inheritanceTester {
 def getConfig[A >: ConfigOne](): A = {
   ConfigOne("test1","testOne")
 }

  def printConfig[A <: ConfigOne](conf:A): Unit  = {
    println(conf.extraArg)
  }
}

class ExtensionTwo extends inheritanceTester {
  def getConfig[A >: ConfigTwo](): A = {
    ConfigTwo("test2","testTwo")
  }

  override def printConfig[A <: ConfigTwo](conf:A): Unit  = {
    println(conf.extraTwo)
  }
}
</code>```

```<code>object Main extends App {

  def run[A <: inheritanceTester](input: A): Unit = {
    val conf = input.getConfig()
    input.printConfig(conf)
  }

  val extensionOne = new ExtensionOne()
  run(extensionOne)

  val extensionTwo = new ExtensionTwo()
  run(extensionTwo)
}

</code>```

at this point I'm getting the following error message when compiling:

Error:(26, 7) overriding method printConfig in trait inheritanceTester of type [A <: collections.ParentConfig](conf: A)Unit;
 method printConfig has incompatible type

Error:(36, 16) overriding method printConfig in trait inheritanceTester of type [A <: collections.ParentConfig](conf: A)Unit;
 method printConfig has incompatible type

It may be just be a silly question with an easy fix. But I'm kinda stuck. Could anyone perhaps point me in the correct direction on where to look? Am I perhaps using these bounds wrong or is this not a direct usecase for a polymorhic function?

答:
Something like this?</p>

```<code>trait ParentConfig{val input : String}

case class ConfigOne(input:String, extraArg:String) extends ParentConfig

case class ConfigTwo(input:String, extraTwo:String) extends ParentConfig
trait InheritanceTester[A <: ParentConfig] {

  def getConfig(): A

  def printConfig(conf: A): Unit
}

class ExtensionOne extends InheritanceTester[ConfigOne] {
  override def getConfig(): ConfigOne = {
   ConfigOne("test1","testOne")
  }

  override def printConfig(conf: ConfigOne): Unit  = {
    println(conf.extraArg)
  }
}

class ExtensionTwo extends InheritanceTester[ConfigTwo] {
  override def getConfig(): ConfigTwo = {
    ConfigTwo("test2","testTwo")
  }

  override def printConfig(conf: ConfigTwo): Unit  = {
    println(conf.extraTwo)
  }
}
object Main extends App {

  def run[A <: ParentConfig](input: InheritanceTester[A]): Unit = {
    val conf = input.getConfig()
    input.printConfig(conf)
  }

  val extensionOne = new ExtensionOne()
  run(extensionOne)

  val extensionTwo = new ExtensionTwo()
  run(extensionTwo)
}
</code>```

Body:
I'm trying out some generic functions in Scala but I seem to be stuck trying to get the following example to work:

I've got the following (simplified) problem. I've got a parent config (which is a trait) and two case classes that inherit from this parent config. They both add one extra argument. Then I further got another Parent trait and 2 subclasses that extend this trait. These subclasses both implement the parents methods, it should have both a get config and a print config function. In my main class I then run a runner function which should first get the config, and subsequently print the config.

What I've tried is: changing the bounds, both in the parent and the children. I've also tried to change the return types. However this does not seem to work.

trait ParentConfig{val input : String}

case class ConfigOne(input:String, extraArg:String) extends ParentConfig

case class ConfigTwo(input:String, extraTwo:String) extends ParentConfig

trait inheritanceTester {

  def getConfig[A >: ParentConfig](): A

  def printConfig[A <: ParentConfig](conf: A): Unit
}

class ExtensionOne extends inheritanceTester {
 def getConfig[A >: ConfigOne](): A = {
   ConfigOne("test1","testOne")
 }

  def printConfig[A <: ConfigOne](conf:A): Unit  = {
    println(conf.extraArg)
  }
}

class ExtensionTwo extends inheritanceTester {
  def getConfig[A >: ConfigTwo](): A = {
    ConfigTwo("test2","testTwo")
  }

  override def printConfig[A <: ConfigTwo](conf:A): Unit  = {
    println(conf.extraTwo)
  }
}

object Main extends App {

  def run[A <: inheritanceTester](input: A): Unit = {
    val conf = input.getConfig()
    input.printConfig(conf)
  }

  val extensionOne = new ExtensionOne()
  run(extensionOne)

  val extensionTwo = new ExtensionTwo()
  run(extensionTwo)
}

at this point I'm getting the following error message when compiling:

Error:(26, 7) overriding method printConfig in trait inheritanceTester of type [A <: collections.ParentConfig](conf: A)Unit;
 method printConfig has incompatible type

Error:(36, 16) overriding method printConfig in trait inheritanceTester of type [A <: collections.ParentConfig](conf: A)Unit;
 method printConfig has incompatible type

It may be just be a silly question with an easy fix. But I'm kinda stuck. Could anyone perhaps point me in the correct direction on where to look? Am I perhaps using these bounds wrong or is this not a direct usecase for a polymorhic function?

Body:
Something like this?

trait ParentConfig{val input : String}

case class ConfigOne(input:String, extraArg:String) extends ParentConfig

case class ConfigTwo(input:String, extraTwo:String) extends ParentConfig
trait InheritanceTester[A <: ParentConfig] {

  def getConfig(): A

  def printConfig(conf: A): Unit
}

class ExtensionOne extends InheritanceTester[ConfigOne] {
  override def getConfig(): ConfigOne = {
   ConfigOne("test1","testOne")
  }

  override def printConfig(conf: ConfigOne): Unit  = {
    println(conf.extraArg)
  }
}

class ExtensionTwo extends InheritanceTester[ConfigTwo] {
  override def getConfig(): ConfigTwo = {
    ConfigTwo("test2","testTwo")
  }

  override def printConfig(conf: ConfigTwo): Unit  = {
    println(conf.extraTwo)
  }
}
object Main extends App {

  def run[A <: ParentConfig](input: InheritanceTester[A]): Unit = {
    val conf = input.getConfig()
    input.printConfig(conf)
  }

  val extensionOne = new ExtensionOne()
  run(extensionOne)

  val extensionTwo = new ExtensionTwo()
  run(extensionTwo)
}


问:
Why am I getting NullPointer Exception in this Android project
I am a beginner in FireBase database. I wrote this code for retrieving user data after authentication. The authentication part is working well but the data retrieving part is crashing my app with this error.

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

at com.kcw.firebasebasics.UserInterface$1.onDataChange(UserInterface.java:58)

  at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@17.0.0:75)

  at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@17.0.0:63)

  at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@17.0.0:55)

  at android.os.Handler.handleCallback(Handler.java:739)

  at android.os.Handler.dispatchMessage(Handler.java:95)

Here is the code that I wrote and I wrote a comment on line 58 (the line causing error) to identify it.

```<code>FirebaseUser firebaseUser;
DatabaseReference reference;
TextView greeting;
String name,text;

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_interface);
    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    reference = FirebaseDatabase.getInstance().getReference()
                                .child(firebaseUser.getUid());
    greeting = findViewById(R.id.greet_msg);

    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                String text = dataSnapshot.getValue().toString();//line 58

            try {
                JSONObject object = new JSONObject(text);
                name = object.getString("username");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String message = "WELCOME ";
            message = message + name.toUpperCase();
            greeting.setText(message);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
</code>```

Help me resolve this.

I verified whether there is any null object in my database and I didn't find any.

I also tried making all my String variables global but that didn't work either

And finally a picture of my database after registering users.

link to database screenshot

答: According to the API documentation, getValue() returns null when there is no data at the location you queried.  You should check if data actually exists() there before calling getValue(), or at least manually check for null before calling toString().</p>

Body:
I am a beginner in FireBase database. I wrote this code for retrieving user data after authentication. The authentication part is working well but the data retrieving part is crashing my app with this error.

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

at com.kcw.firebasebasics.UserInterface$1.onDataChange(UserInterface.java:58)

  at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@17.0.0:75)

  at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@17.0.0:63)

  at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@17.0.0:55)

  at android.os.Handler.handleCallback(Handler.java:739)

  at android.os.Handler.dispatchMessage(Handler.java:95)

Here is the code that I wrote and I wrote a comment on line 58 (the line causing error) to identify it.

FirebaseUser firebaseUser;
DatabaseReference reference;
TextView greeting;
String name,text;

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_interface);
    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    reference = FirebaseDatabase.getInstance().getReference()
                                .child(firebaseUser.getUid());
    greeting = findViewById(R.id.greet_msg);

    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                String text = dataSnapshot.getValue().toString();//line 58

            try {
                JSONObject object = new JSONObject(text);
                name = object.getString("username");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String message = "WELCOME ";
            message = message + name.toUpperCase();
            greeting.setText(message);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

Help me resolve this.

I verified whether there is any null object in my database and I didn't find any.

I also tried making all my String variables global but that didn't work either

And finally a picture of my database after registering users.

link to database screenshot


问:
How to update queryset value in django?
I have written a python script in my project. I want to update the value of a field.

Here are my modes

```<code>
class News_Channel(models.Model):
    name = models.TextField(blank=False)
    info = models.TextField(blank=False)
    image = models.FileField()
    website = models.TextField()
    total_star = models.PositiveIntegerField(default=0)
    total_user = models.IntegerField()

    class Meta:
        ordering = ["-id"]

    def __str__(self):
        return self.name

class Count(models.Model):
    userId = models.ForeignKey(User, on_delete=models.CASCADE)
    channelId = models.ForeignKey(News_Channel, on_delete=models.CASCADE)
    rate = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.channelId.name

    class Meta:
        ordering = ["-id"]
</code>```

This is my python script:

```<code>from feed.models import Count, News_Channel

def run():
    for i in range(1, 11):
        news_channel = Count.objects.filter(channelId=i)
        total_rate = 0
        for rate in news_channel:
            total_rate += rate.rate
        print(total_rate)
        object = News_Channel.objects.filter(id=i)
        print(total_rate)
        print("before",object[0].total_star,total_rate)
        object[0].total_star = total_rate
        print("after", object[0].total_star)
        object.update()

</code>```

After counting the total_rate from the Count table I want to update the total star value in News_Channel table. I am failing to do so and get the data before the update and after the update as zero. Although total_rate has value.

答:
The reason is that object in your case is a queryset, and after you attempt to update object[0], you don't store the results in the db, and don't refresh the queryset. To get it to work you should pass the field you want to update into the update method.

So, try this:

```<code>def run():
    for i in range(1, 11):
        news_channel = Count.objects.filter(channelId=i)
        total_rate = 0
        for rate in news_channel:
            total_rate += rate.rate
        print(total_rate)
        object = News_Channel.objects.filter(id=i)
        print(total_rate)
        print("before",object[0].total_star,total_rate)
        object.update(total_star=total_rate)
        print("after", object[0].total_star)
</code>```

Title: How to update queryset value in django?

Body:
I have written a python script in my project. I want to update the value of a field.

Here are my modes

class News_Channel(models.Model):
    name = models.TextField(blank=False)
    info = models.TextField(blank=False)
    image = models.FileField()
    website = models.TextField()
    total_star = models.PositiveIntegerField(default=0)
    total_user = models.IntegerField()

    class Meta:
        ordering = ["-id"]

    def __str__(self):
        return self.name

class Count(models.Model):
    userId = models.ForeignKey(User, on_delete=models.CASCADE)
    channelId = models.ForeignKey(News_Channel, on_delete=models.CASCADE)
    rate = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.channelId.name

    class Meta:
        ordering = ["-id"]

This is my python script:

from feed.models import Count, News_Channel

def run():
    for i in range(1, 11):
        news_channel = Count.objects.filter(channelId=i)
        total_rate = 0
        for rate in news_channel:
            total_rate += rate.rate
        print(total_rate)
        object = News_Channel.objects.filter(id=i)
        print(total_rate)
        print("before",object[0].total_star,total_rate)
        object[0].total_star = total_rate
        print("after", object[0].total_star)
        object.update()

After counting the total_rate from the Count table I want to update the total star value in News_Channel table. I am failing to do so and get the data before the update and after the update as zero. Although total_rate has value.

Body:
The reason is that object in your case is a queryset, and after you attempt to update object[0], you don't store the results in the db, and don't refresh the queryset. To get it to work you should pass the field you want to update into the update method.

So, try this:

def run():
    for i in range(1, 11):
        news_channel = Count.objects.filter(channelId=i)
        total_rate = 0
        for rate in news_channel:
            total_rate += rate.rate
        print(total_rate)
        object = News_Channel.objects.filter(id=i)
        print(total_rate)
        print("before",object[0].total_star,total_rate)
        object.update(total_star=total_rate)
        print("after", object[0].total_star)