I have started to learn Hibernate and such error has appeared:
exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.ExceptionInInitializerError
logic.HibernateUtil.<clinit>(HibernateUtil.java:16)
logic.DefaultTableDAO.getItems(DefaultTableDAO.java:38)
servlet.TestServlet.doGet(TestServlet.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:267)
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231)
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240)
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
logic.HibernateUtil.<clinit>(HibernateUtil.java:14)
logic.DefaultTableDAO.getItems(DefaultTableDAO.java:38)
servlet.TestServlet.doGet(TestServlet.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100)
org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54)
org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:257)
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231)
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240)
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
logic.HibernateUtil.<clinit>(HibernateUtil.java:14)
logic.DefaultTableDAO.getItems(DefaultTableDAO.java:38)
servlet.TestServlet.doGet(TestServlet.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I use Tomcate 8.5.6, Java 8, Hibernate and postgresql 9.5.2.
JDBC Driver 9.4-1201
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:postgresql://localhost:5432/postgres?charSet=LATIN1</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.username">postgres</property>
<property name="connection.password">java1235</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
<property name="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().buildSessionFactory();
} catch (Throwable e){
throw new ExceptionInInitializerError(e);
}
}
private HibernateUtil(){}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
The class which calls Hibernate
package servlet;
import logic.DefaultTable;
import logic.DefaultTableDAO;
import logic.Factory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class TestServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(1);
list.add(1);
list.add(1);
list.add(1);
Factory factory = Factory.getInstance();
DefaultTableDAO table = factory.getItemDao();
List<DefaultTable> items = null;
try {
items = table.getItems();
} catch (SQLException e) {
e.printStackTrace();
}
req.setAttribute("listItem", list);
req.setAttribute("str", items.get(0).getPartName());
req.getRequestDispatcher("/WEB-INF/my_page.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("NOOOOOOOOOOOOOOOOOO");
}
}
log Tomcate
05-Nov-2016 15:44:39.412 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 846 ms
05-Nov-2016 15:44:46.519 INFO [http-nio-80-exec-1] org.hibernate.Version.logVersion HHH000412: Hibernate Core {5.2.4.Final}
05-Nov-2016 15:44:46.522 INFO [http-nio-80-exec-1] org.hibernate.cfg.Environment.<clinit> HHH000206: hibernate.properties not found
05-Nov-2016 15:44:46.524 INFO [http-nio-80-exec-1] org.hibernate.cfg.Environment.buildBytecodeProvider HHH000021: Bytecode provider name : javassist
05-Nov-2016 15:44:46.567 INFO [http-nio-80-exec-1] org.hibernate.annotations.common.reflection.java.JavaReflectionManager.<clinit> HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
05-Nov-2016 15:44:46.730 WARN [http-nio-80-exec-1] org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator.initiateService HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections
05-Nov-2016 15:44:46.733 WARN [http-nio-80-exec-1] org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService HHH000342: Could not obtain connection to query metadata : The application must supply JDBC connections
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
05-Nov-2016 15:46:49.454 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.core.StandardContext.reload Reloading Context with name [] has started
05-Nov-2016 15:46:49.986 INFO [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.core.StandardContext.reload Reloading Context with name [] is completed
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
The current error is because you did not configure the hibernate.dialect properly, you can set it as below in your hibernate.cfg.xml file:
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
Also, ensure that the other properties are set with right property names:
hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = yoururl
hibernate.connection.username = youruserid
hibernate.connection.password = yourpwd
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
You can refer here
Related
Issue - I am using mac OS Mojave, I have created one program which will create a table in the db named HibernateTutorials, I have installed Ampps and started it on 3306 port to create db. Now whenever i try to create table I am getting below error.
Error -
Mar 15, 2019 1:10:34 AM org.hibernate.Version logVersion
WARN: HHH000342: Could not obtain connection to query metadata : Unable to resolve name [org.hibernate.dialect.MySQDialect] as strategy [org.hibernate.dialect.Dialect]
Exception in thread "main" 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)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:175)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:119)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:84)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:474)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:85)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:689)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at com.gontuseries.hibernate.Main.main(Main.java:23)
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.MySQDialect] as strategy [org.hibernate.dialect.Dialect]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:133)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:212)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:160)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:147)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:141)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:74)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:51)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
... 14 more
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.dialect.MySQDialect]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:136)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:129)
... 24 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.dialect.MySQDialect
at org.hibernate.boot.registry.classloading.internal.AggregatedClassLoader.findClass(AggregatedClassLoader.java:210)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:133)
... 25 more
Please find the below classes I have created -
Main class -
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.fasterxml.classmate.AnnotationConfiguration;
public class Main {
public static void main(String[] args) {
Student_Info stu = new Student_Info();
stu.setName("Aniket");
stu.setRoll_no(1);
Configuration con = new Configuration().configure().addAnnotatedClass(Student_Info.class);
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(stu);
session.getTransaction().commit();
session.close();
sf.close();
}
}
Student_Info -
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="STUDENT_INFORMATION")
public class Student_Info {
#Id
private int roll_no;
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
hibernate.cfg.xml -
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/HibernateTutorials</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool(use the built in) -->
<property name="connection.pool_size">1</property>
<!-- sql dialect -->
<property name="dialect">org.hibernate.dialect.MySQDialect</property>
<!-- Disable the second level cache -->
<property name="cache.provider_clas">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed sql to stdout -->
<property name="show_sql">true</property>
<!-- Drop the existing tables and create new one -->
<property name="hbm2ddl.auto">create</property>
<!-- Mention here all the model classes along with their package name -->
<mapping class="com.gontuseries.hibernate.Student_Info" />
</session-factory>
</hibernate-configuration>
Note - please suggest if the problem is in configuration or in code as the code I think is good;
You have typing error in dialect configuration
org.hibernate.dialect.MySQDialect
I'm new in Hibernate and I'm trying to create a little aplication in Java using Maven in IntelliJ Idea.
I'm having this error in title above, and answers of the same problem here on Stack did not helped me until now.
What is this file "Person.hbm.xml". I have to create it?
Once it is a mapping resource, Hibernate should not create it itself?
I'm getting this error when I run my little program:
Exception in thread "main" org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not found : HibernateExposed/Person.hbm.xml : origin(HibernateExposed/Person.hbm.xml)
at org.hibernate.boot.spi.XmlMappingBinderAccess.bind(XmlMappingBinderAccess.java:56)
at org.hibernate.boot.MetadataSources.addResource(MetadataSources.java:274)
at org.hibernate.boot.cfgxml.spi.MappingReference.apply(MappingReference.java:70)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:412)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:86)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at Persistencia.HibernateUtils.<init>(HibernateUtils.java:10)
at Main.Main.main(Main.java:16)
This is my class of database configuration: HibernateUtils:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
//Fábrica de sessões de banco de dados constante no padrão SINGLETON
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
And bellow, my entity class that I'm trying to persist:
import javax.persistence.Entity;
import java.sql.Date;
#Entity
public class Produto {
private String nome;
private int cod;
private float valor;
private Date dataValidade;
protected Produto() {
}
public Produto(String nome, int cod, float valor, Date dataValidade) {
this.nome = nome;
this.cod = cod;
this.valor = valor;
this.dataValidade = dataValidade;
}
/*public Produto getProdutoPorNome(String nome) {
Produto buscaResult = //Resultado da busca.
}
*/
public boolean excluirProduto(int cod) {
boolean deuCerto=false;
return deuCerto;
}
}
And my Main class:
package Main;
import Persistencia.HibernateUtils;
import ProcessoDeVenda.Produto;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Session sessao;
HibernateUtils hiber = new HibernateUtils();
SessionFactory session = hiber.getSessionFactory();
Produto produto;
try {
sessao = session.openSession();
Date data = new Date(05, 12, 2018);
float valor = (float) 42000.0;
produto = new Produto("Carro", 1, valor, (java.sql.Date) data);
System.out.println(produto.toString());
}catch (Exception sqlException) {
System.out.println(sqlException);
}
}
}
The project structure, with the location of hibernate.cfg.xml file.
And my hibernate.cfg.xml file content:
Look at the "mapping resource" tag.
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:~/PDV</property>
<property name="connection.username">Lucas</property>
<property name="connection.password">mypass</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="HibernateExposed/Person.hbm.xml" />
</session-factory>
</hibernate-configuration>
Now, i'm trying to map classes direct on hibernate.cfg.xml. (Why hibernate does not make this itself? I'm using anotations...)
I've deleted
<mapping resource="HibernateExposed/Person.hbm.xml" />
ANd in i'ts place I've mapped the class:
<mapping class="src.main.java.ProcessoDeVenda.Produto" />
And the error just changed to this:
Exception in thread "main" 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:271)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:417)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:86)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at Persistencia.HibernateUtils.<init>(HibernateUtils.java:10)
at Main.Main.main(Main.java:16)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:105)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.addConnections(DriverManagerConnectionProviderImpl.java:363)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:282)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.<init>(DriverManagerConnectionProviderImpl.java:260)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections$Builder.build(DriverManagerConnectionProviderImpl.java:401)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:112)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:75)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
... 15 more
Caused by: org.h2.jdbc.JdbcSQLException: Database may be already in use: null. Possible solutions: close all other connection(s); use the server mode [90020-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
at org.h2.message.DbException.get(DbException.java:168)
at org.h2.mvstore.db.MVTableEngine$Store.convertIllegalStateException(MVTableEngine.java:188)
at org.h2.mvstore.db.MVTableEngine$Store.open(MVTableEngine.java:168)
at org.h2.mvstore.db.MVTableEngine.init(MVTableEngine.java:100)
at org.h2.engine.Database.getPageStore(Database.java:2538)
at org.h2.engine.Database.open(Database.java:709)
at org.h2.engine.Database.openDatabase(Database.java:286)
at org.h2.engine.Database.<init>(Database.java:280)
at org.h2.engine.Engine.openSession(Engine.java:66)
at org.h2.engine.Engine.openSession(Engine.java:179)
at org.h2.engine.Engine.createSessionAndValidate(Engine.java:157)
at org.h2.engine.Engine.createSession(Engine.java:140)
at org.h2.engine.Engine.createSession(Engine.java:28)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:351)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:124)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:103)
at org.h2.Driver.connect(Driver.java:69)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 30 more
Caused by: java.lang.IllegalStateException: The file is locked: nio:C:/Users/Lucas_Pletsch/PDV.mv.db [1.4.197/7]
at org.h2.mvstore.DataUtils.newIllegalStateException(DataUtils.java:870)
at org.h2.mvstore.FileStore.open(FileStore.java:173)
at org.h2.mvstore.MVStore.<init>(MVStore.java:350)
at org.h2.mvstore.MVStore$Builder.open(MVStore.java:2934)
at org.h2.mvstore.db.MVTableEngine$Store.open(MVTableEngine.java:155)
... 45 more
This is my H2 database console, showing the configurations that I have passed to hibernate.cfg.xml, like JDBC URL, driver class...
I have imported H2 in POM.xml file of my project:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
You can either define entity mapping via annotations (I prefer this) or in an XML file. Based on the error it is looking for xml file Person.hbm.xml in folder HibernateExposed (see it from your config file <mapping resource="HibernateExposed/Person.hbm.xml" />). So you need to create Person.hbm.xml file with name of entity and all attributes. E.g.
<entity-mappings>
<entity class="your_package_name.Produto" name="Produto">
<attributes>
<property name="nome"
type="value"
not-null="value"
update="value"/>
//put all other attributes from Produto class
</attributes>
</entity>
</entity-mappings>
But in this case you do not need to use #Entity annotation. If you want to use annotations then change hibernate.cfg.xml to something like <mapping class="your_package_name.Produto"/>
I solved the problems configuring hibernate using hibernate.properties file, instead of hibernate.cfg.xml.
I used H2 in memory, using the jdbc URL (one of the defaults in H2): jdbc:h2:mem:test, configured at hibernate.properties. (More in this link: http://www.h2database.com/html/features.html#database_url)
I've follow all the steps of this tutorial for the solution: https://www.youtube.com/watch?v=MA4tM17H6_M
I am trying to create a encrypted value in the properties for hibernate.connection.password. At run time the encrypted value is picked up and decrypted. I then try to overwrite the properties in the HibernateUtil. But even after decryption the value doesn't seemed to be used because it fails to authenticate. How would I get this to work?
public class HibernateUtil {
private static final SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
private static final String keyFile="/keys/.aoo1key";
static {
try {
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
String passwordToDecrypt=cfg.getProperty("hibernate.connection.password");
if(passwordToDecrypt.startsWith("ENC(")&&passwordToDecrypt.endsWith(")")) {
passwordToDecrypt = passwordToDecrypt.substring(4,passwordToDecrypt.length()-1);
PropertiesEncryption propertiesEncryption = new PropertiesEncryption(keyFile);
String decrypted = propertiesEncryption.decryptValue(passwordToDecrypt);
cfg.setProperty("hibernate.connection.password", decrypted);
}
StandardServiceRegistry standardRegistry = cfg.getStandardServiceRegistryBuilder().build();
Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
} catch (Throwable th) {
System.err.println("Enitial SessionFactory creation failed" + th);
throw new ExceptionInInitializerError(th);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate5</property>
<property name="hibernate.connection.username">root</property>
<!-- <property name="hibernate.connection.password">dog</property> -->
<property name="hibernate.connection.password">ENC(MYFBqlDom8ZawVi+toB3PU0MdI10Desvsq4D2Z5lejk=)</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="net.model.Employee" />
</session-factory>
</hibernate-configuration>
The Exception
Enitial SessionFactory creation failedorg.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Exception in thread "main" java.lang.ExceptionInInitializerError
at net.roseindia.HibernateUtil.<clinit>(HibernateUtil.java:66)
at net.roseindia.GetAllData.main(GetAllData.java:18)
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:271)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at net.roseindia.HibernateUtil.<clinit>(HibernateUtil.java:60)
... 1 more
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:105)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.addConnections(PooledConnections.java:123)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:42)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:20)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:161)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:109)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:72)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
... 13 more
Caused by: java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:910)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3923)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1273)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2031)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 28 more
I found that if I broke it down into steps I can get it to do what I want. I was doing the build at the same time I was instantiating the StandardServiceRegistry. That seems to have been the main problem with my code. Plus I found that I should set the decrypted password with standardServiceRegistryBuilder.applySetting and not with the Configuration object.
StandardServiceRegistry standardRegistry = cfg.getStandardServiceRegistryBuilder().build();
it works like this
public class HibernateUtil {
private static StandardServiceRegistry serviceRegistry;
private static SessionFactory sessionFactory =buildSessionFactory();
private static final String keyFile="/keys/.aoo1key";
// Hibernate 5:
private static SessionFactory buildSessionFactory() {
try {
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
// Create the ServiceRegistry from hibernate.cfg.xml
StandardServiceRegistryBuilder standardServiceRegistryBuilder = cfg.getStandardServiceRegistryBuilder();
//Get the encrypted value
String passwordToDecrypt=cfg.getProperty("hibernate.connection.password");
//Test if it is encrypted
if(passwordToDecrypt.startsWith("ENC(")&&passwordToDecrypt.endsWith(")")) {
//Stripping "ENC(" and ")"
passwordToDecrypt = passwordToDecrypt.substring(4,passwordToDecrypt.length()-1);
//TODO Key file is the key to use for decrytion, the name of my class PropertiesEncryption is kind of bad, what should I call it?
PropertiesEncryption propertiesEncryption = new PropertiesEncryption(keyFile);
String decrypted = propertiesEncryption.decryptValue(passwordToDecrypt);
//Overwrite the encrypted value
standardServiceRegistryBuilder.applySetting("hibernate.connection.password", decrypted);
}
//This will build even if the password wasn't never encrypted
serviceRegistry =standardServiceRegistryBuilder.build();
// Create a metadata sources using the specified service registry.
Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();
return metadata.getSessionFactoryBuilder().build();
} catch (Throwable ex) {
if (serviceRegistry != null) {
StandardServiceRegistryBuilder.destroy(serviceRegistry);
}
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
// getSessionFactory().close();
if (serviceRegistry != null) {
StandardServiceRegistryBuilder.destroy(serviceRegistry);
}
}
}
I'm setting up a Hibernate project without hibernate.xml.
So I configured Hibernate like this:
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Configuration cnf = new Configuration();
// Properties
cnf.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
cnf.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/test_db?useSSL=false");
cnf.setProperty("hibernate.connection.username", "root");
cnf.setProperty("hibernate.connection.password", "root");
cnf.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
cnf.setProperty("hibernate.hbm2ddl.auto", "update");
cnf.setProperty("hibernate.show_sql", "true");
cnf.setProperty(" hibernate.connection.pool_size", "1");
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(cnf.getProperties());
sessionFactory = cnf.buildSessionFactory(builder.build());
// Class mappings
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
When I execute the Hibernate logs this line:
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/test_db?useSSL=false]
After executing I get this exception:
Exception in thread "main" java.lang.ExceptionInInitializerError
at core.Tester.main(Tester.java:10)
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:271)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at database.HibernateUtil.<clinit>(HibernateUtil.java:34)
... 1 more
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:105)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.addConnections(PooledConnections.java:123)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:42)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:20)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:161)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:109)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:72)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
... 14 more
Caused by: java.sql.SQLException: The connection property 'useSSL' only accepts values of the form: 'true', 'false', 'yes' or 'no'. The value 'false' is not in this set.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.validateStringValues(ConnectionPropertiesImpl.java:314)
at com.mysql.jdbc.ConnectionPropertiesImpl$BooleanConnectionProperty.initializeFrom(ConnectionPropertiesImpl.java:91)
at com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.initializeFrom(ConnectionPropertiesImpl.java:216)
at com.mysql.jdbc.ConnectionPropertiesImpl.initializeProperties(ConnectionPropertiesImpl.java:2503)
at com.mysql.jdbc.ConnectionImpl.initializeDriverProperties(ConnectionImpl.java:3153)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:774)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 29 more
I don't see what I could be doing wrong since it logs out the connection URL as expected. And I don't see how it could be an encoding error.
I have spent a few hours trying to set up my first Hibernate application and it still doesn't work.
I have WAMP Server with my MySQL Data Base called "hibernatetest". I have Project in Eclipse, which contains Hibernate library, and mysql-connector-java-5.1.18-bin.jar. I have also this classes:
HibernateUtil.java:
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory(
new StandardServiceRegistryBuilder().build() );
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
test.java (contains main):
import org.hibernate.Session;
import templates.Album;
public class test {
public static void main(String[] args){
Album i = new Album();
i.setID(1);
i.setArtist("Iron Maiden");
i.setTitle("The Book of Souls");
i.setLabel("Warner Music");
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(i);
session.getTransaction().commit();
session.close();
System.out.println("Saved");
}
}
Album.java:
package templates;
public class Album {
private int ID;
private String title;
private String artist;
private String label;
public Album(){
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
Album.hbm.xml: link
Hibernate.cfg.xml: link
StackTrace:
wrz 15, 2015 10:04:47 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.1.Final}
wrz 15, 2015 10:04:47 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
wrz 15, 2015 10:04:47 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
wrz 15, 2015 10:04:47 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
wrz 15, 2015 10:04:48 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.0.Final}
wrz 15, 2015 10:04:49 PM org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator initiateService
WARN: HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections
wrz 15, 2015 10:04:49 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata : The application must supply JDBC connections
Initial SessionFactory creation failed.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Exception in thread "main" java.lang.ExceptionInInitializerError
at HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
at HibernateUtil.<clinit>(HibernateUtil.java:7)
at test.main(test.java:13)
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:244)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
at HibernateUtil.buildSessionFactory(HibernateUtil.java:12)
... 2 more
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)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
... 15 more
What am I doing wrong?
As the error says, you need to specify the dialect in your hibernate.cfg file.
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
I had the same problem . just add your port number after localhost .in my case it is localhost:3306
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_db</property>
This is how I fixed my error.
My environment is same as yours Hibernate 5+, Mysql & WAMP Server
Make sure you include jta jar which is included at this location \hibernate-release-5.0.5.Final\lib\osgi
You should add new user and grant all privileges. And the HOST should be localhost
And your hibernate.cfg.xml should look like this
Thats how it worked for me. I figured I had to give localhost and NOT %
I noticed some things that may be causing the trouble:
1) In your hibernate.cfg.xml you are not specifying the password for your connection. You can do so by adding the <property name="connection.password">your_Pass_here</property> property (or did you ommit it for privacy reasons?)
2) as #Prerak Tiwari mentioned, you are not specifying the Dialect. Do so as he mentioned with the <property name="dialect">org.hibernate.dialect.MySQLDialect</property> property
3) I notice that the name of you properties is different as the ones most people use. Instead of adding ...name="hibernate.connection.driver_class"... ommit the hibernate. part, so it should look like this:
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernatetest</property>
<property name="connection.username">root</property>
Your password property here...
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="/templates/Album.hbm.xml"/>
</session-factory>
Hope some of this works for you :)
Check for passwor is correct or not in hibernate.cfg.xml
<property name="connection.password">root</property>