I am new to hibernate. While running my first program I am facing 2 errors.
Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] and
Unable to make JDBC Connection ["jdbc:mysql://localhost:3306/practiceDB"]
Dependencies in pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.8.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
JAVA code
Configuration cfg=new Configuration();
cfg.configure();
SessionFactory factory=cfg.buildSessionFactory();
System.out.println(factory);
CodePudding user response:
When using Spring you don't always need to write a configuration class for your database connection (atleast if you only have one single datasource).
You can simply configure your datasource via your application.properties
or application.yaml
file.
Try adding this to your application.properties
file:
spring.datasource.url=jdbc:mysql://localhost:3306/practiceDB
spring.datasource.username=yourUsername
spring.datasource.password=yourPassword
Or adding this to your application.yaml
file:
spring:
datasource:
url: jdbc:mysql://localhost:3306/practiceDB
username: yourUsername
password: yourPassword
This should allow you to establish a connection to your datasource.
CodePudding user response:
By default, Hibernate uses its internal database connection pool library. That means it keeps a database connection open to be reused later. And MySQL database server has a timeout value for each connection (default is 8 hours or 28,800 seconds). So if a connection has been idle longer than this timeout value, it will be dropped by the server. Therefore, when the Java database application has been idle longer than MySQL server’s connection timeout value, and the end user tries to connect again, Hibernate reuses the idle connection which was already dropped by the server, hence JDBCConnectionExceptionis thrown.
Expiring and/or testing connection validity before use in your application: This requires changing or re-structuring the existing code, which is difficult to implement. Furthermore, opening a database connection is an expensive operation so it’s not optimal to open and close database connection for every user’s request - that’s why database connection pooling comes into play.