How to solve following ServiceException in Hibernate + Weblogic (JNDI) application? - java

I have a JNDI created on my Weblogic Server 12c. I am trying to connect to the Oracle database on the server using datasource and create a table there using hibernate. But I keep getting same exception org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] Part 1 Part 2. This exception comes after I submit id and name from index.jsp
Please see my java code and suggest any changes:
Versions:
Java 8
Weblogic 12c
Hibernate 5
Oracle 11g
Project Structure
Jar Files
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.datasource">java:comp/env/jdbc/Abc</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping class="packone.Bean"/>
</session-factory>
</hibernate-configuration>
Context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/Abc"
auth="container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:#//RAPC01-1702-26:1521/P1130PL2"
username="root"
password="root"
maxActive="100"
maxIdle="20"
minIdle="5"
maxWait="10000">
</Resource>
</Context>
HibernateUtil.java:
private static StandardServiceRegistry standardServiceRegistry;
private static SessionFactory sessionFactory;
public Session getSession(List<String> list) {
list.add("START: getsession");
if(sessionFactory == null) {
try {
standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
Metadata metadata = metadataSources.getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch(Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
list.add(sw.toString());
}
}
list.add("END: getsession");
return sessionFactory.openSession();
}
web.xml:
Just containts welcome file list as index.jsp
index.jsp:
<%
List<String> list = (List<String>)request.getAttribute("lsit");
if(list==null) {
} else {
for(String str: list) {
%> <%=str %><br> <%
}
}
%>
<form action="BeanServlet">
<input type="text" name="id" placeholder="Enter Id...">
<input type="text" name="name" placeholder="Enter Name...">
<input type="submit">
</form>
Bean.java:
package packone;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Bean {
#Id
private int id;
private String name;
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;
}
}
BeanServlet.java:
List<String> list = new ArrayList<>();
list.add("servlet started");
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
list.add("id value: "+id);
list.add("name value: "+name);
Bean B = new Bean();
B.setId(id);
B.setName(name);
new BeanDAO().createBean(B, list);
list.add("servlet before RD");
request.setAttribute("lsit", list);
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
BeanDAO.java:
package packone;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import org.hibernate.Session;
public class BeanDAO {
public void createBean(Bean B, List<String> list) {
Session session = null;
try {
list.add("START: DAO");
session = new HibernateUtil().getSession(list);
list.add("Arriva Session");
session.beginTransaction();
session.save(B);
session.getTransaction().commit();
list.add("END: DAO");
} catch(Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
list.add(sw.toString());
} finally {
if(session != null) {
session.flush();
session.close();
}
}
}
}
Let me know if you need more details or if question formatting needs improvement. Not an expert on Weblogic btw. Thanks.

Everything looks fine to me.
Try using ojdbc6.jar instead of ojdbc14.jar. As your Oracle is version 11 and java is 8. ojdbc14.jar is very old now.
Let me know if it works.

Related

Hibernate SQLite: Cannot get a connection as the driver manager is not properly initialized

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

How to connect to SQL Server 2017 using Hibernate and Windows Authentication?

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>

i am Getting org.hibernate.InvalidMappingException: Unable to read XML while running simple hibernate project

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 can't get get the SessionFactory in Hibernate 5.1.0. My code breaks in the line while getting the SessionFactory obj

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.

Hibernate user lacks privilege or object not found error

I have created a java application which will select ceratin values from the table and print it using hibernate.I have used HSQLDb as the back end.But after executing I am getting the error
user lacks privilege or object not found:
But iam getting the query when i execute for the first time as
Hibernate: select ifmain0_.IF_ID as IF1_0_, ifmain0_.IF_NAME as IF2_0_ from IF_MAIN ifmain0_
But after that i am getting the above error. So i deleted the sample.lck file and after executing two times again I am getting the same error
ERROR org.hibernate.util.JDBCExceptionReporter - user lacks privilege or object not found: IF_MAIN
org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.loader.Loader.doList(Loader.java:2545)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
at org.hibernate.loader.Loader.list(Loader.java:2271)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:459)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:365)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1268)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
at org.mock.Mainclass.listNAMES(Mainclass.java:31)
at org.mock.Mainclass.main(Mainclass.java:22)
Caused by: java.sql.SQLException: user lacks privilege or object not found: IF_MAIN
at org.hsqldb.jdbc.Util.sqlException(Util.java:224)
at org.hsqldb.jdbc.JDBCPreparedStatement.<init>(JDBCPreparedStatement.java:3885)
at org.hsqldb.jdbc.JDBCConnection.prepareStatement(JDBCConnection.java:641)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:534)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:452)
at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1700)
at org.hibernate.loader.Loader.doQuery(Loader.java:801)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.doList(Loader.java:2542)
... 9 more
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: IF_MAIN
at org.hsqldb.error.Error.error(Error.java:77)
at org.hsqldb.SchemaManager.getTable(SchemaManager.java:685)
at org.hsqldb.ParserDQL.readTableName(ParserDQL.java:5297)
at org.hsqldb.ParserDQL.readTableOrSubquery(ParserDQL.java:1662)
at org.hsqldb.ParserDQL.XreadTableReference(ParserDQL.java:1074)
at org.hsqldb.ParserDQL.XreadFromClause(ParserDQL.java:1061)
at org.hsqldb.ParserDQL.XreadTableExpression(ParserDQL.java:996)
at org.hsqldb.ParserDQL.XreadQuerySpecification(ParserDQL.java:990)
at org.hsqldb.ParserDQL.XreadSimpleTable(ParserDQL.java:974)
at org.hsqldb.ParserDQL.XreadQueryPrimary(ParserDQL.java:903)
at org.hsqldb.ParserDQL.XreadQueryTerm(ParserDQL.java:869)
at org.hsqldb.ParserDQL.XreadQueryExpressionBody(ParserDQL.java:848)
at org.hsqldb.ParserDQL.XreadQueryExpression(ParserDQL.java:822)
at org.hsqldb.ParserDQL.compileCursorSpecification(ParserDQL.java:5449)
at org.hsqldb.ParserCommand.compilePart(ParserCommand.java:133)
at org.hsqldb.ParserCommand.compileStatement(ParserCommand.java:63)
at org.hsqldb.Session.compileStatement(Session.java:906)
at org.hsqldb.StatementManager.compile(StatementManager.java:335)
at org.hsqldb.Session.execute(Session.java:1009)
at org.hsqldb.jdbc.JDBCPreparedStatement.<init>(JDBCPreparedStatement.java:3882)
My hibernate config file is
org.hsqldb.jdbcDriver
jdbc:hsqldb:file:C:/Users/298637/SAMPLE;hsqldb.lock_file=false
org.hibernate.dialect.HSQLDialect
sa
sa
1
thread
org.hibernate.cache.NoCacheProvider
true
none
Mapping file is
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.mock">
<class name="IFMAIN" table="IF_MAIN ">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="number" type="string" column="IF_ID">
<generator class="native"/>
</id>
<property name="name" column="IF_NAME" type="string"/>
</class>
</hibernate-mapping>
Pojo CLASS
public class IFMAIN {
private String number;
private String name ;
public IFMAIN()
{
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Main class
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Mainclass {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Mainclass ME = new Mainclass();
ME.listNAMES();
}
public void listNAMES( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List sample = session.createQuery("FROM IFMAIN").list();
int i=0;
for (Iterator iterator = sample.iterator(); iterator.hasNext();){
IFMAIN count = (IFMAIN) iterator.next();
System.out.println("SITE CODE: " + count.getNumber());
System.out.println("SITE DESCRIPTION: " + count.getName());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
Can anybody tell me why I am getting this error. I tried with other db like mysql and oracle 10g. there Iam able to connect and get the result but when I am using the HSQL Db I am getting this error

Categories

Resources