@yuradun

Почему не удается подключиться к удаленной базе данных через Spring Boot JPA?

На хостинге находится MySQL база данных версии 10.3, к которой пытаюсь подключиться, но как бы ни старался крашит с множеством ошибок.

Удаленный доступ на хостинге настроил, подключаться к хосту может каждый.
Если посмотреть через phpmyadmin, то MySQL запущена на localhost:3306.

Проверял через приложение для удаленного подключение к бд Sequel PRO задавая данные для подключения - все работало с полным доступом. Соответсвенно проблема не на стороне хостинга.

Также поднимал локальный сервер с MySQL, где также поменяв лишь данные в файле application.properties без труда присоединился и создавал сущности.

Мог бы кто объяснить в чем дело и как следует подключиться к удаленной бд?

Файл контроллера запросов
package com.example.API.Controllers.UserAuthControllers;

import com.example.API.Models.UserPassword;
import com.example.API.Repositories.AuthRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class RegistrationController {

    @Autowired
    private AuthRepository authRepository;

    @PostMapping("/auth/registrationCreateRequest")
    public String test(
            @RequestParam(value = "login") String login,
            @RequestParam(value = "passwordHASH") String passwordHASH
    ) {
        UserPassword userPassword = new UserPassword(login, passwordHASH);
        authRepository.save(userPassword);
        return "ok";
    }
}


Файл сущности для бд
package com.example.API.Models;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "users_pwd")
public class UserPassword {

    @Id
    @GeneratedValue
    private int id;
    private String login;
    private String passwordHASH;

    public UserPassword(String login, String passwordHASH) {
        this.login = login;
        this.passwordHASH = passwordHASH;
    }

    public UserPassword() {
    }

    public long getId() {
        return id;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPasswordHASH() {
        return passwordHASH;
    }

    public void setPasswordHASH(String passwordHASH) {
        this.passwordHASH = passwordHASH;
    }
}


Файл репозитория
package com.example.API.Repositories;

import com.example.API.Models.UserPassword;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface AuthRepository extends JpaRepository<UserPassword, Integer> {
}


Файл application.properties
# MySQL BD CONNECTION
spring.jpa.database=mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://remoteHost:3306/bdname
spring.datasource.username=username
spring.datasource.password=pwd
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=none


Файл 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 https://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.5.6</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>API</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>project</name>
	<description>desc</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<version>2.5.7</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.27</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
			<version>2.5.7</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.6.1.Final</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.13.0</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
			<version>2.5.6</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<version>5.6.0</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

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

</project>


Здесь привел ниже заголовки ошибок, при краше приложения, причем ошибка "The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server." вылетает аж несколько раз, думаю в ней самый сок, но не получилось спросить у гугла или ответы были не рабочие для меня.

2021-11-19 15:54:36.642  WARN 58707 --- [           main] o.h.e.j.e.i.JdbcEnvironmentInitiator     : HHH000342: Could not obtain connection to query metadata

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution

Caused by: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
Caused by: org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution

Process finished with exit code 1
  • Вопрос задан
  • 1211 просмотров
Решения вопроса 1
azerphoenix
@azerphoenix Куратор тега Java
Java Software Engineer
Добрый вечер!
No appropriate protocol (protocol is disabled or cipher suites are inappropriate)

А так пробовали?
jdbc:mysql://remoteHost:3306/bdname?autoReconnect=true&useSSL=false

https://stackoverflow.com/questions/67899129/postf...
А вот, что говорят:
As far as I am concerned, the cause of the issue is that OpenJdk requires TLSv1.2 or TLSv1.3, starting from version 11.0.11. Update: The change will apply to at least OpenJDK 8u292 onward, OpenJDK 11.0.11 onward, and all versions of OpenJDK 16, following the JRE and JDK Crypto Roadmap published by Oracle
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽
25 апр. 2024, в 15:51
3000 руб./за проект
25 апр. 2024, в 15:31
70000 руб./за проект
25 апр. 2024, в 15:26
15000 руб./за проект