Hibernate user lacks privilege or object not found error - java

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

Related

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>

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

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.

Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection using mySQL

I am trying to run a simple java project to see the working of hibernate but when i am executing my code it gives a hibernate exception, i am using mysql 5.6 and eclipse neon,i even checked for grant access and everything seems to be fine, please help Here is the code:
main.java
package com.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Session session = null;
SessionFactory sessionFactory= null;
//create sessionFactory
sessionFactory= new Configuration().configure().buildSessionFactory();
// create Session
session=sessionFactory.openSession();
// create and begin transaction
Transaction t = session.beginTransaction();
//create contact object and set values to the object
Contact contact = new Contact();
contact.setId(101);
contact.setFirstName("Dina");
contact.setLastName("adams");
contact.setEmailID("dina.adams#gmail.com");
// insert record by saving session
session.save(contact);
session.flush();
// commit transaction
t.commit();
//close the session
session.close();
}
}
contact.java
package com.demo;
public class Contact {
//properties
private String firstName;
private String lastName;
private String emailID;
private int id;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailID() {
return emailID;
}
public void setEmailID(String emailID) {
this.emailID = emailID;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/emp</property>
<property name="hibernate.connection.usename">rajesh</property>
<property name="hibernate.connection.password">Nepal123</property>
<property name="hibernate.connection.poolsize">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping file -->
<mapping resource="Contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
contact.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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.demo.Contact" table="Contact">
<id column= "ID" name="id" type= "int" >
<generator class = "assigned"></generator>
</id>
<property name = "firstName">
<column name="FIRST NAME"></column>
</property>
<property name="lastName">
<column name="LAST NAME"></column>
</property>
<property name="emailID">
<column name ="EMAIL ID"></column>
</property>
</class>
</hibernate-mapping>
error message:-
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:426)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
at com.demo.Main.main(Main.java:25)
Caused by: java.sql.SQLException: Access denied for user ''#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:875)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1712)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1228)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:423)
... 5 more
Check out this tag:
<property name="hibernate.connection.usename">rajesh</property>
the name should be hibernate.connection.username instead of hibernate.connection.usename.

Invalid Object Name for Hibernate Sequence Generator

I am developing an application that accesses a database running SQL Server 2012 through the Hibernate framework. However, I cannot figure out how to make an instance of the SequenceGenerator annotation work; I get an exception whenever I attempt to save a new object instance to my database table. The class to be saved is the following:
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name="MESSAGES")
public class Message implements Serializable {
private static final long serialVersionUID = -3535373804021266134L;
#Id
#Column(name="MESSAGE_ID")
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="MESSAGE_GEN")
#SequenceGenerator(name="MESSAGE_GEN", sequenceName="MESSAGE_SEQ", initialValue=1, allocationSize=1)
private Long id;
#Column(name="TEXT")
private String text;
public Message(String text) {
this.text = text;
}
public Long getId() {
return id;
}
public String getText() {
return text;
}
}
An issue-provoking scenario could be the following transaction:
import org.hibernate.Session;
public class Manager {
public static void main(String[] args) {
Session session = Database.getSessionFactory().getCurrentSession();
session.beginTransaction();
Message message = new Message("Hello, World!");
session.save(message);
session.getTransaction().commit();
Database.getSessionFactory().close();
}
}
This results in the following stack trace related to the identifier sequence:
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
at org.hibernate.id.SequenceGenerator.generateHolder(SequenceGenerator.java:122)
at org.hibernate.id.SequenceHiLoGenerator.generate(SequenceHiLoGenerator.java:73)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:356)
at com.sun.proxy.$Proxy8.save(Unknown Source)
at dk.radiometer.tests.hibernate.service.Manager.doTransaction(Manager.java:35)
at dk.radiometer.tests.hibernate.service.Manager.main(Manager.java:16)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'MESSAGE_SEQ'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:285)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
... 19 more
The issue seems related to the name of the sequence. My guess is that I need to manually create a sequence table of some sort for Hibernate to use, however, I do not know how to do this an have been unable to find a resource that seems related to my environment. If this is indeed the issue, please redirect me to some documentation for the protocol to follow. In addition, I am using the following programmatic Hibernate configuration:
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class Database {
private static final SessionFactory SESSION_FACTORY = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration cfg = buildConfiguration();
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
SessionFactory sf = cfg.buildSessionFactory(sr);
return sf;
} catch (Throwable t) {
System.err.println("Initial SessionFactory creation failed: " + t);
throw new ExceptionInInitializerError(t);
}
}
private static Configuration buildConfiguration() {
return new Configuration()
.addAnnotatedClass(Message.class)
.setProperty("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver")
.setProperty("hibernate.connection.url", "jdbc:sqlserver://SERVER_NAME;databaseName=DATABASE_NAME;integratedSecurity=true;")
.setProperty("hibernate.connection.pool_size", "1")
.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServer2012Dialect")
.setProperty("hibernate.current_session_context_class", "thread")
.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.internal.NoCacheProvider")
.setProperty("hibernate.show_sql", "true")
.setProperty("hibernate.hbm2ddl.auto", "update");
}
public static SessionFactory getSessionFactory() {
return SESSION_FACTORY;
}
}
Thanks in advance!
The solution to this issue is adding the catalog and schema properties to your #Table annotation.
#Table(name="<<TableName>>", catalog="<<DatabaseName>>", schema="SchemaName")
e.g
#Table(name="EVENTS", catalog="EVENTMANAGER", schema="DBO")
Catalog refers to the database name where the given table belongs
to.
Schema refers to the container (using oracle definition) to which
the database belongs, in microsoft SQL Server, databases are
generally created under the Database Operator (DBO) schema.
e.g. Hibernata Mapping File (hbm) which works for me.
<class name="Event" table="EVENTS" catalog="EVENTMANAGER" schema="DBO">
<id name="id" column="EVENT_ID">
<generator class="native"/>
</id>
<property name="date" type="timestamp" column="EVENT_DATE"/>
<property name="title" column="TITLE" not-null="true"/>
</class>

Unable to call Stored procedure from hibernate

Please try to answer the problem in the below code for calling a stored procedure in ORACLE from hibernate . i am using a named query in hbm file to be called from the testclient.java .
Hibernate3.2.1 core file is being used.
My stored procedure:
create or replace procedure get_empdetails2(mycursor out sys_refcursor, cond in varchar2)
as
begin
open mycursor for
select eb.first_name,eb.last_name from employee3 eb where eb.email like cond ;
end;
Employee.java:
public class Employee{
public Employee()
{
}
private int eid;
private String fname,lname,email;
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
table employee3:
Column Name Data Type Nullable Default Primary Key
EID NUMBER Yes - -
FIRST_NAME VARCHAR2(20) Yes - -
LAST_NAME VARCHAR2(20) Yes - -
EMAIL VARCHAR2(20) Yes - -
hibernate.cfg:
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name='connection.url'>jdbc:oracle:thin:#localhost:1521/xe</property>
<property name='connection.username'>system</property>
<property name='connection.password'>oracle123</property>
<property name='connection.driver_class'>oracle.jdbc.driver.OracleDriver</property>
<property name="show_sql">true</property>
<mapping resource="employee3.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Testclient.java
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.hibernate.Criteria;
public class TestClient
{
private static SessionFactory factory;
public static void main(String[] args)
{
System.out.println("--------------done-----------");
Configuration cfg= new Configuration();
System.out.println("--------------got cfg object-----------");
cfg = cfg.configure("hibernate.cfg.xml");
System.out.println("--------------hbm loaded into cfg-----------");
SessionFactory sf= cfg.buildSessionFactory();
System.out.println("--------------done-----------");
System.out.println("--------------getting session-----------");
Session ses =sf.openSession();
Transaction tx = ses.beginTransaction();
System.out.println("--------------got tx object-----------");
Employee eb =null;
SQLQuery q1=(SQLQuery)ses.getNamedQuery("test1");
//q1.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
System.out.println("--------------q1 processing-----------");
//q1.setInteger(0,0);
q1.setString(0,"v%");
//q1.setParameter(0, "%a%");
System.out.println("--------------q1 processing-----------");
List res=q1.list();
System.out.println(res);
tx.commit();
ses.close();
System.out.println("--------------closing connection-----------");
sf.close();
System.out.println("--------------connection closed-----------");
}}
employee3.hbm:
<?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>
<class name="Employee" table="employee3">
<id name="eid" column="eid"/>
<property name="fname" column="first_name"/>
<property name="lname" column="last_name"/>
<property name="email" column="email"/>
</class>
<sql-query name="test1" callable="true">
<return alias ="test1" class ="Employee">
<return-property name="fname" column="FIRST_NAME"/>
<return-property name="lname" column="LAST_NAME"/>
</return>
{call get_empdetails2(?,?)}
</sql-query>
</hibernate-mapping>
In the call get_empdetails(?,?) , the first ? is used for output mycursor which as per the hibernate doc must be the first parameter and second ? is the input parameter for the cond variable in procedure.
My output error is :
Oct 10, 2014 2:38:54 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: indexes: [] Oct 10, 2014 2:38:54 PM
org.hibernate.tool.hbm2ddl.SchemaUpdateexecuteINFO:schema update complete
--------------done-----------
--------------getting session-----------
--------------got tx object-----------
--------------q1 processing-----------
--------------q1 processing-----------
Hibernate: {call get_empdetails2(?,?)}
Oct 10, 2014 2:38:54 PM org.hibernate.type.NullableType nullSafeGet
INFO: **could not read column value from result set: eid0_0_; Invalid column name**
Oct 10, 2014 2:38:54 PM org.hibernate.util.JDBCExceptionReporter logExceptions
WARNING: SQL Error: 17006, SQLState: null
Oct 10, 2014 2:38:54 PM org.hibernate.util.JDBCExceptionReporter logExceptions
SEVERE: Invalid column name Exception in thread "main"
org.hibernate.exception.GenericJDBCException: could not execute query at
org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.doList(Loader.java:2214)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2095)
at org.hibernate.loader.Loader.list(Loader.java:2090)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:289)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1695)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:142)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:150)
at TestClient.main(TestClient.java:44)
Caused by: java.sql.SQLException: Invalid column name
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
As present in the output , i am getting this - could not read column . whats wrong in the configuration?
Thanks
Hibernate is trying to map whole table from return result of Stored Procedure. You are returning eb.first_name,eb.last_name from Stored Procedure.
Possible Solution 1:
Select all field in Stored Procedure SELECT query like select * from employee3 eb where eb.email like cond ;
If solution 1 works for you then use it but if you want to return only two fields from stored procedure I'd suggest you second solution. As I don't know how we can execute named query which returns only selected fields.
Possible Solution 2:
Use SQLQuery. I used it with MySQL You can try for Oracle. Hope it will work.
Query callStoredProcedure_MYSQL = session.createSQLQuery("CALL SP_MYSQL_HIBERNATE (:param1, :param2, :param3)");
callStoredProcedure_MYSQL.setInteger("param1", 10);
callStoredProcedure_MYSQL.setInteger("param2", 10);
callStoredProcedure_MYSQL.setString("param3", "test");*/
/* callStoredProcedure_MYSQL.list() will execute stored procedure and return the value */
List customResult = callStoredProcedure_MYSQL.list();
if (customResult != null && !customResult.isEmpty()) {
Object[] obj = customResult.get(0);
System.out.println(obj[0]);
System.out.println(obj[1]);
}
We have the same error but I resolve it by just adding my database name where my stored procedure is located:
Query query = session.createSQLQuery("CALL db_Name.storeprocedureName(:parameter)");

Categories

Resources