Full MCVE is at the bottom of this post.
I am trying to run a very basic Hibernate example as I work through a tutorial. However, I am receiving the following error: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]:
Exception in thread "main" java.lang.ExceptionInInitializerError
at hibernateTutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:50)
at hibernateTutorial.util.HibernateUtil.getSessionFactory(HibernateUtil.java:30)
at hibernateTutorial.main.HibernateMain.main(HibernateMain.java:21)
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)
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:176)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:127)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:86)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:479)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:85)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:709)
at hibernateTutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:47)
... 2 more
Caused by: org.vibur.dbcp.ViburDBCPException: java.lang.NullPointerException
at org.vibur.dbcp.ViburDBCPDataSource.start(ViburDBCPDataSource.java:233)
at org.hibernate.vibur.internal.ViburDBCPConnectionProvider.configure(ViburDBCPConnectionProvider.java:57)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:107)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:246)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
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:101)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
... 15 more
Caused by: java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:460)
at java.util.Properties.setProperty(Properties.java:166)
at org.vibur.dbcp.pool.Connector$Builder$Driver.<init>(Connector.java:66)
at org.vibur.dbcp.pool.Connector$Builder$Driver.<init>(Connector.java:56)
at org.vibur.dbcp.pool.Connector$Builder.buildConnector(Connector.java:48)
at org.vibur.dbcp.ViburDBCPDataSource.doStart(ViburDBCPDataSource.java:248)
at org.vibur.dbcp.ViburDBCPDataSource.start(ViburDBCPDataSource.java:226)
... 24 more
My database is on a Microsoft SQL Server 2017 instance that uses Windows Authentication. I have added both the MSSQL JDBC (v6.4.0) updated IntelliJ with the -Djava.library.path VM option so that sqljdbc_auth.dll (required for Windows Authentication) is accessible.
From what I can tell in my research into this ambiguous error message, it could have many different causes, but ultimately boils down to just not being able to connect to the database somehow. Most of the other Q&A I've found seems to be specific to other databases or SQL Server that doesn't use Windows Authentication.
I have copied the JDBC URL directly from my datasource config in IntelliJ so I know that it is correct and works properly in the IDE.
What else is required to properly configure Hibernate to connect to SQL Server?
HibernateMain.java:
package hibernateTutorial.main;
import hibernateTutorial.model.Employee;
import hibernateTutorial.util.HibernateUtil;
import org.hibernate.Session;
import java.time.LocalDateTime;
public class HibernateMain {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setName("Nathan");
emp.setRole("CEO");
emp.setInsertTime(LocalDateTime.now());
// **********************************************************************************************
// Get Session
// **********************************************************************************************
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
// **********************************************************************************************
// Start transaction
// **********************************************************************************************
session.beginTransaction();
// **********************************************************************************************
// Save the model object
// **********************************************************************************************
session.save(emp);
// **********************************************************************************************
// Commit the transaction
// **********************************************************************************************
session.getTransaction().commit();
System.out.println("Employee ID: " + emp.getId());
// **********************************************************************************************
// Terminate the session factory or the program won't end
// **********************************************************************************************
HibernateUtil.getSessionFactory().close();
}
}
HibernateUtil.java:
package hibernateTutorial.util;
import hibernateTutorial.model.Employee1;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import java.util.Properties;
public class HibernateUtil {
// **********************************************************************************************
// XML-based configuration
// **********************************************************************************************
private static SessionFactory sessionFactory;
// **********************************************************************************************
// Annotation-based configuration
// **********************************************************************************************
private static SessionFactory sessionAnnotationFactory;
// **********************************************************************************************
// Property-based configuration
// **********************************************************************************************
private static SessionFactory sessionJavaConfigFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
private static SessionFactory buildSessionFactory() {
try {
// **********************************************************************************************
// Create the SessionFactory from hibernate.cfg.xml
// **********************************************************************************************
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate serviceRegistry created");
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable e) {
System.err.println("Initial SessionFactory creation failed. " + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionAnnotationFactory() {
if (sessionAnnotationFactory == null) sessionAnnotationFactory = buildSessionAnnotationFactory();
return sessionAnnotationFactory;
}
private static SessionFactory buildSessionAnnotationFactory() {
try {
// **********************************************************************************************
// Create the SessionFactory from hibernate-annotation.cfg.xml
// **********************************************************************************************
Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable e) {
System.err.println("Initial SessionFactory creationg failed." + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionJavaConfigFactory() {
if (sessionJavaConfigFactory == null) sessionJavaConfigFactory = buildSessionJavaConfigFactory();
return sessionJavaConfigFactory;
}
private static SessionFactory buildSessionJavaConfigFactory() {
try {
Configuration configuration = new Configuration();
//Create Properties, can be read from property files too
Properties props = new Properties();
props.put("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
props.put("hibernate.connection.url", "jdbc:sqlserver://FADBOKT2493V\\KRAFTLAKEODB:51678;database=Dev_RepAssistDB;integratedSecurity=true");
props.put("hibernate.current_session_context_class", "thread");
configuration.setProperties(props);
//we can set mapping file or class with annotation
//addClass(Employee1.class) will look for resource
// com/journaldev/hibernate/model/Employee1.hbm.xml (not good)
configuration.addAnnotatedClass(Employee1.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Java Config serviceRegistry created");
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
}
Employee.java:
package hibernateTutorial.model;
import java.time.LocalDateTime;
public class Employee {
private int id;
private String name;
private String role;
private LocalDateTime insertTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public LocalDateTime getInsertTime() {
return insertTime;
}
public void setInsertTime(LocalDateTime insertTime) {
this.insertTime = insertTime;
}
}
Employee1.java:
package hibernateTutorial.model;
import javax.persistence.*;
import java.time.LocalDateTime;
#Entity
#Table(name = "tmp_employees",
uniqueConstraints =
{#UniqueConstraint(columnNames = {"id"})})
public class Employee1 {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, unique = true, length = 11)
private int id;
#Column(name = "name", length = 20, nullable = true)
private String name;
#Column(name = "role", length = 20, nullable = true)
private String role;
#Column(name = "insert_time", nullable = true)
private LocalDateTime insertTime;
}
employee.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernateTutorial.model.Employee" table="tmp_employees">
<id name="id" type="int">
<column name="id"/>
<generator class="increment"/>
</id>
<property name="name" type="java.lang.String">
<column name="name"/>
</property>
<property name="role" type="java.lang.String">
<column name="role"/>
</property>
<property name="insertTime" type="java.time.LocalDateTime">
<column name="insert_time"/>
</property>
</class>
</hibernate-mapping>
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://servername:port;
database=test_db;integratedSecurity=true
</property>
<!-- Connection Pool Size -->
<property name="hibernate.connection.pool_size">5</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Outputs the SQL queries, should be disabled in Production -->
<property name="hibernate.show_sql">true</property>
<!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</property>
<!-- mapping file, we can use Bean annotations too -->
<mapping resource="hibernateTutorial/employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate-annotation.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver:servername:port;database=test_db;integratedSecurity=true</property>
<!-- Connection Pool Size -->
<property name="hibernate.connection.pool_size">5</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Outputs the SQL queries, should be disabled in Production -->
<property name="hibernate.show_sql">true</property>
<!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</property>
<!-- mapping with model class containing annotations -->
<mapping class="hibernateTutorial.model.Employee1"/>
</session-factory>
</hibernate-configuration>
Related
I try to make use a Database system without have to run a separate database program.
I decided to use Hibernate SQLite. And I'm getting desperate here.
can someone pls tell me what i am doing whrong, or where i can find more help? I Faild with google, and ChatGPT was as always not helpfull to.
And for every one how try to convince me to use for example MariaDB, no. I need it to be one java application. Not more, not less...
src\main\resources\hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- <property name="hibernate.connection.url">jdbc:sqlite:path/to/your/database.db</property> -->
<property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.connection.url">jdbc:sqlite:database.db</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="de.minetrain.kekbot.database.test.Person"/>
</session-factory>
</hibernate-configuration>
src\main\resources\persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd" version="2.2">
<persistence-unit name="my-persistence-unit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>de.minetrain.kekbot.database.test.Person</class>
<!-- <class>com.example.MyOtherEntity</class> -->
<properties>
<property name="hibernate.connection.driver_class" value="org.sqlite.JDBC" />
<!-- <property name="hibernate.connection.url" value="jdbc:sqlite:path/to/your/database.db" /> -->
<property name="hibernate.connection.url" value="jdbc:sqlite:database.db" />
<property name="hibernate.connection.username" value="" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLiteDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<!-- <property name="hibernate.show_sql" value="true" /> -->
</properties>
</persistence-unit>
</persistence>
pom.xml
</ependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.1.Final</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.34.0</version>
</dependency>
</dependencies>
HibernateUtil class:
package de.minetrain.kekbot.database.test;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HibernateUtil {
private static final Logger logger = LoggerFactory.getLogger(HibernateUtil.class);
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
logger.error("Dant find class: ",e);
}
try {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); // may wrong?
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
return configuration.buildSessionFactory(builder.build());
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Entity class:
package de.minetrain.kekbot.database.test;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Person {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
private int age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
And the class i try to whrite into the database:
package de.minetrain.kekbot.database.test;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class Database {
public static void test(){
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
// Verwenden Sie die Session, um Datenbankoperationen auszuführen
// session.close();
Transaction tx = null;
try {
tx = session.beginTransaction();
Person person = new Person();
person.setName("Max Mustermann");
person.setAge(30);
session.save(person);
tx.commit();
} catch (HibernateException ex) {
if (tx != null) {
tx.rollback();
}
ex.printStackTrace();
} finally {
session.close();
}
}
}
I just wanna lern to use SQLite, and try to Whrite a new person object into a database file.
Errors:
[20:00:15] >> WARN << [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator] - HHH000342: Could not obtain connection to query metadata java.lang.IllegalStateException: Cannot get a connection as the driver manager is not properly initialized
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
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.SQLiteDialect] as strategy [org.hibernate.dialect.Dialect]
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.dialect.SQLiteDialect]
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.dialect.SQLiteDialect
I've managed to change the Exeptions. With the help from #andrewJames I found out, that I have to use a dialect, which I didn't know. I also noticed that I am using old versions of Hibernate and co.
And sorry in advance, for every experienced coder how gets headaches from my stupidity. I am not new to coding, but I am very new to databases and dealing with dependency's outside from just API package things. I tried to google as much as I could find, and testing every thing I could. But I ended up having to ask again. I am very sorry.
Iive changed stuff around and now have this pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.6.Final</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.40.0.0</version>
</dependency>
<dependency>
<groupId>com.github.gwenn</groupId>
<artifactId>sqlite-dialect</artifactId>
<version>0.1.2</version>
</dependency>
I've changed the dialect in the hibernate.cfg.xml:
<property name="hibernate.dialect">org.sqlite.hibernate.dialect.SQLiteDialect</property>
persistence.xml:
<property name="hibernate.dialect" value="org.sqlite.hibernate.dialect.SQLiteDialect" />
However, now I get the benefit of dealing with this exception:
[00:07:48] >> INFO << [org.hibernate.Version] - HHH000412: Hibernate ORM core version 6.1.6.Final
Initial SessionFactory creation failed.java.util.ServiceConfigurationError: org.hibernate.boot.spi.MetadataBuilderInitializer: Provider org.sqlite.hibernate.dialect.SQLiteMetadataBuilderInitializer could not be instantiated
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.util.ServiceConfigurationError: org.hibernate.boot.spi.MetadataBuilderInitializer: Provider org.sqlite.hibernate.dialect.SQLiteMetadataBuilderInitializer could not be instantiated
Caused by: java.lang.NoClassDefFoundError: org/hibernate/dialect/function/SQLFunction
Caused by: java.lang.ClassNotFoundException: org.hibernate.dialect.function.SQLFunction
I'm running my first hibernate project which saves user information such as id,name and address into mysql database
This is my error log
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.InvalidMappingException: Unable to read XML
at org.hibernate.internal.util.xml.MappingReader.readMappingDocument(MappingReader.java:109)
at org.hibernate.cfg.Configuration.add(Configuration.java:490)
at org.hibernate.cfg.Configuration.add(Configuration.java:486)
at org.hibernate.cfg.Configuration.add(Configuration.java:659)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:742)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2197)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2169)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2149)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2102)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2017)
at mypack.DataInsertion.insertInfo(DataInsertion.java:18)
at mypack.DataInsertion.main(DataInsertion.java:11)
Caused by: org.dom4j.DocumentException: Error on line 3 of document : The processing instruction target matching "[xX][mM][lL]" is not allowed. Nested exception: The processing instruction target matching "[xX][mM][lL]" is not allowed.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.internal.util.xml.MappingReader.readMappingDocument(MappingReader.java:78)
... 11 more
hibernate.cfg.xml (Configuration xml file)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibdb</property>
<property name="connection.user">root</property>
<property name="connection.password">admin</property>
<!-- Related to the connection END -->
<!-- Related to the hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Related to the hibernate properties END -->
<!-- List of XML mapping files -->
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
user.hbm.xml (Mapping xml)
<!-- Mapping File to POJO Class -->
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="mypack.DataProvider" table="user_info">
<id name="user_id" column="table_id">
<generator class="assigned"/>
</id>
<property name="user_name" column = "name" />
<property name="user_address" column = "address" />
</class>
</hibernate-mapping>
DataProvider.java (POJO class)
//POJO Class
package mypack;
public class DataProvider {
private int user_id;
private String user_name;
private String user_address;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_address() {
return user_address;
}
public void setUser_address(String user_address) {
this.user_address = user_address;
}
}
DataInsertion.java (Implentation java class)
package mypack;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DataInsertion {
public static void main(String[] args) {
new DataInsertion().insertInfo();
}
public void insertInfo()
{
Configuration con = new Configuration(); //interation with hib
con.configure("hibernate.cfg.xml"); //registering to xml
SessionFactory SF = con.buildSessionFactory(); //creating session
Session session = SF.openSession(); //opening new session
DataProvider provider = new DataProvider();
provider.setUser_id(1);
provider.setUser_name("Goutham");
provider.setUser_address("Hunsur");
Transaction TR = session.beginTransaction();
session.save(provider);
System.out.println("Object saved successfully");
TR.commit(); //saving transaction
session.close();
SF.close();
}
}
Please advise me,,,
Thanks.
Try removing the comment line and blank line before the first tag in user.hbm.xml
I'm trying to test the hibernate configuration of a project, but when I try to run the test it throws a MappinException saying that it does not known my entity, I checked the database and it is not creating the tables either, so my guess is that it is not reading the mapping files, but I checked that and the path is correct. And the package and class properties inside the mapping files is also correct (supposely).
Most of the questions I read are Annotation Focused, does anyone has an idea what's happening under the hood?
Thanks in advance
I have the following directory structure:
The hibernate.cfg.xml file it's like follows:
<hibernate-configuration>
<session-factory>
<!-- Hibernate Configuration -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.hbm2ddl.auto">
update
</property>
<!-- Database Configuration -->
<property name="hibernate.connection.url">
jdbc:mysql://127.0.0.1:3306/library_management?createDatabaseIfNotExist=true
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
cetys
</property>
<!-- Class Mapping Files -->
<mapping resource="Hibernate.config/mapping/Book.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/Classification.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/Collection.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/Loan.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/NonExistentRegistry.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The Loan mapping file is:
<hibernate-mapping package="com.cetys.cetyslibraryinventory.Core.DomainModels">
<class name="Loan" table="loan">
<meta attribute="class-description">
This class contains the basic information for a Loan
</meta>
<id name="id" column="loan_id" type="int"></id>
<many-to-one name="bookId" class="Book" unique="true"
column="book_id" cascade="all"/>
</class>
</hibernate-mapping>
The model:
package com.cetys.cetyslibraryinventory.Core.DomainModels;
//imports ommited
public class Loan implements Catalogable {
private int id;
private int book_id;
protected Loan () {
}
public Loan ( int id, int book_id ) {
this.id = id;
this.book_id = book_id;
}
// Getters and Setters Ommited
}
And when I try to run the following:
public class Program {
public static void main ( String[] args ) {
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try {
Configuration configuration = new Configuration();
configuration.configure( "hibernate.cfg.xml" );
ServiceRegistry serviceRegistry
= new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties() ).build();
sessionFactory = configuration.
buildSessionFactory( serviceRegistry );
session = sessionFactory.openSession();
Loan ln = new Loan( 0, 0 );
tx = session.beginTransaction();
session.save( ln );
tx.commit();
} catch ( Exception e ) {
LOGGER.log( Level.SEVERE, e.getMessage(), e );
} finally {
if ( session != null ) {
session.close();
}
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
}
}
Exception Error:
SEVERE: Unknown entity: com.cetys.cetyslibraryinventory.Core.DomainModels.Loan
org.hibernate.MappingException: Unknown entity: com.cetys.cetyslibraryinventory.Core.DomainModels.Loan
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1533)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
at com.cetys.cetyslibraryinventory.Program.main(Program.java:74)
Jun 08, 2016 10:04:41 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://127.0.0.1:3306/library_management?createDatabaseIfNotExist=true]
Image
ERROR:
1) AdminModel.java - Model class.
2) HibernateUtil.java facilitates the Hibernate DB conn.
3) AdminDAO.java - u guyz know what these are...I'll save the pain to explain...and oh yes...m already through days of pain with this bug ...trynna debug...i've got deadlines to meet... if u guyz could help me it'd be a matter of great deal...
public class AdminModel {
private int adminID;
private String username;
private String password;
public int getAdminID() {
return adminID;
}
public void setAdminID(int adminID) {
this.adminID = adminID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
HibernateUtil.java
public class HibernateUtil {
public static SessionFactory sessionFactory;
static {
try {
/* File f=new File("O:/#workspace/#eclipse/ekatabookstore.com/src/hibernate.cfg.xml");
sessionFactory =new Configuration().configure(f).buildSessionFactory();
*/
/****OR****/
String hibernatePropsFilePath = "O:/#workspace/#eclipse/ekatabookstore.com/src/hibernate.cfg.xml";
File hibernatePropsFile = new File(hibernatePropsFilePath);
Configuration configuration = new Configuration();
configuration.configure(hibernatePropsFile);
configuration.addResource("ekatabookstore.hbm.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
//throw new ExceptionInInitializerError(ex);
}
}
public static Session openSession() {
return HibernateUtil.sessionFactory.openSession();
//return sessionFactory.getCurrentSession();
}
}
AdminDAO.java
public AdminDAO(AdminModel adminUserObj) {
public void createAdmin() {
/*
* CRUD operation of HIBERNATE C-->Create SessionFactory Object is a
* heavy object and takes up huge resources, so it is better to create
* only one object and share it where needed.
*/
SessionFactory sessionFactoryObj = HibernateUtil.sessionFactory;
// System.out.println(sessionFactoryObj.getClass().getName());
Session session = sessionFactoryObj.openSession();
session.beginTransaction();// Transaction Started
session.save(adminObj);// SAVED
session.getTransaction().commit();// Transaction Ended
System.out.println("!!!SUCCESSFUL CREATE!!!");
session.close();// CLOSE session resource of Hibernate
Notification.notificationMsg = "ADMIN CREATE - SUCCESSFUL!";
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.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/ekatabookstoreDB</property>
<property name="connection.username">xyz</property>
<property name="connection.password">xyz</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</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.internal.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">create</property> -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="ekatabookstore.hbm.xml" />
</session-factory>
</hibernate-configuration>
hbn.properties
hiberNateCfgFileName=hibernate.cfg.xml
ekatabookstore.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.ekatabookstore.layer.service.model.AdminModel" table="admin">
<id name="adminID" type="integer" column="id_admin">
<generator class="assigned" />
</id>
<property name="username" type="string" column="username" not-null="true" />
<property name="password" type="string" column="password" not-null="true" />
</class>
</hibernate-mapping>
If you are using spring then, Add autowire on sessionfactory or get it from application context. You can use following code
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextProvider implements ApplicationContextAware{
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
return context;
}
#Override
public void setApplicationContext(ApplicationContext ac)
throws BeansException {
context = ac;
}
}
You can use this class anywhere in your code like
ApplicationContextProvider.getApplicationContext().getBean("sessionFactory");
Please try the following code for creating sessionfactory
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
StandardServiceRegistryBuilder.destroy( registry );
}
Hope this helps.
I am doing the introductory tutorial on Hibernate from PluralSight.
For my database, I am using MYSQL.
In my main method, I am creating an object and I am trying to save it.
However, I get the following error:
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.simpleprogrammer.User
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1447)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:678)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:670)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:665)
at com.simpleprogrammer.Program.main(Program.java:16)
My main method is:
public static void main(String[] args) {
System.out.println("Hello World!");
Session session = HibernateUtilities.getSessionFactory().openSession();
session.beginTransaction();
User user = new User();
user.setName("Joe");
user.setGoal(250);
session.save(user);
session.getTransaction().commit();
session.close();
HibernateUtilities.getSessionFactory().close();
}
The error appears on the line with session.save(user);
My Utilities class:
package com.simpleprogrammer;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtilities {
private static SessionFactory sessionFactory;
private static StandardServiceRegistryBuilder ssrb;
static
{
try
{
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(ssrb.build());
}
catch(HibernateException exception)
{
System.out.println("Problem creating session factory");
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
My hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">appuser</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3307</property>
<property name="hibernate.connection.username">appuser</property>
<property name="hibernate.default_schema">protein_tracker</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="com/simpleprogrammer/User.hbm.xml"/>
</session-factory
</hibernate-configuration>
I am sorry to post all this code, but I'm not sure which part is relevant.
I suspect that my error is caused by the database connection, but I'm not sure how to check that.
I had a syntactic error on the line:
</session-factory
This was in hibernate.cfg.xml
This is my first contribution to stackoverflow.com. And I was facing similar error,but now I resolved it by this given solution. So, I am writing this Answer.
You have to change your utility file like this:
static
{
try
{
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
//ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory();
}
catch(HibernateException exception)
{
System.out.println("Problem creating session factory");
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
ssrb variable declaration and definition must be removed.
put configuration.buildSessionFactory(); instead of configuration.buildSessionFactory(ssrb.build());