Unable to call Stored procedure from hibernate - java

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)");

Related

ORA-02289: sequence does not exist after upgrading from hibernate 3.2 to 5.2.12

Below is the code which was working in hibernate 3.2
public class Hibernate3Session {
public static void main(String[] args) throws Exception{
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
org.hibernate.Transaction tr = session.beginTransaction();
Employee emp = new Employee();
emp.setName("Employee1");
emp.setContactNumber("111111");
emp.setAddress("XYZ location");
session.save(emp);
tr.commit();
session.close();
System.exit(0);
}
}
Below are the Employee Table
CREATE TABLE Employee
(
ID NUMBER(10) NOT NULL,
NAME VARCHAR2(50 CHAR) NOT NULL,
CONTACT_NUMBER VARCHAR2(50 CHAR),
ADDRESS VARCHAR2(50 CHAR),
PRIMARY KEY (ID)
);
and the sequences used for the same
CREATE SEQUENCE SEQ_EMPLOYEE_ID
MINVALUE 1
NOMAXVALUE
INCREMENT BY 1 START WITH 1 NOCACHE NOCYCLE ;
Below is the hibernate.cfg.xml file
<?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="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:dbname</property>
<property name="connection.username">SYSTEM</property>
<property name="connection.password">systempassword</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="show_sql">true</property>
<mapping resource="Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
Below are the corresponding Employee.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="Employee" table="EMPLOYEE" >
<id name="id" type="long" >
<column name="ID" />
<generator class="sequence">
<param name="sequence">SEQ_EMPLOYEE_ID</param>
</generator>
</id>
<property name="name" type="string">
<column name="NAME" length="50" not-null="true" />
</property>
<property name="contactNumber" type="string">
<column name="CONTACT_NUMBER" length="50" />
</property>
<property name="address" type="string">
<column name="ADDRESS" length="50" />
</property>
</class>
</hibernate-mapping>
Below are the corresponding POJO classes for the same
public class Employee {
private Long id;
private String name;
private String contactNumber;
private String address;
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 String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((contactNumber == null) ? 0 : contactNumber.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (contactNumber == null) {
if (other.contactNumber != null)
return false;
} else if (!contactNumber.equals(other.contactNumber))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
The code using for hibernate 5.2 final version is as below
public class Hibernate5vSession {
public static void main(String[] args) throws Exception{
SessionFactory sessionFactory = null;
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml");
MetadataSources sources = new MetadataSources(registryBuilder.build());
//sources.addResource("EmployeeRegistration.hbm.xml");
Metadata metaData = sources.getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
Session session = sessionFactory.openSession();
org.hibernate.Transaction tr = session.beginTransaction();
Employee emp = new Employee();
emp.setName("Employee1");
emp.setContactNumber("111111");
emp.setAddress("XYZ location");
session.save(emp);
tr.commit();
session.close();
System.exit(0);
}
}
Also changed the Dialect below:
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
Getting below error
Hibernate: select hibernate_sequence.nextval from dual
Mar 06, 2018 7:56:02 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 2289, SQLState: 42000
Mar 06, 2018 7:56:02 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-02289: sequence does not exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:69)
at org.hibernate.id.enhanced.SequenceStructure$1.getNextValue(SequenceStructure.java:95)
at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:452)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:691)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:683)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:678)
at HibernateSessionFactory.main(HibernateSessionFactory.java:62)
Caused by: java.sql.SQLException: ORA-02289: sequence does not exist
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:305)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:272)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:626)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:185)
at oracle.jdbc.driver.T4CPreparedStatement.execute_for_describe(T4CPreparedStatement.java:503)
at oracle.jdbc.driver.OracleStatement.execute_maybe_describe(OracleStatement.java:951)
at oracle.jdbc.driver.T4CPreparedStatement.execute_maybe_describe(T4CPreparedStatement.java:535)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1046)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:2905)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:2946)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60)
... 13 more
Note: Have verified the Privileges at Oracle. The table is present in admin user System schema and the same is used for credentials.
I have obtained the SessionFactory as mentioned here.
In console it looks from hibernate sequence rather than Oracle
Hibernate: select hibernate_sequence.nextval from dual
Mar 06, 2018 10:26:47 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 2289, SQLState: 42000
why this is not working when i upgrade the hibernate version to 5.2.12
Any help in this?.

hibernate xml configuration seems not to work

I am learning hibernate, and trying to make xml configuration which seems not to work.
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">87654321</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/protein_tracker</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.default_schema">protein_tracker</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="com/andrei/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The <property name="hibernate.hbm2ddl.auto">create</property> does not work. I get exception: no available table in the database.
User.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.andrei.User" table="Users">
<id name="id" type="int">
<column name="ID" />
<generator class="identity" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="total" type="int">
<column name="TOTAL" />
</property>
<property name="goal" type="int">
<column name="GOAL" />
</property>
</class>
</hibernate-mapping>
In the user.hbm.xml I specify that the table is users, but the app looks for table user, which is exactly the name name of my entity.
User.class:
#Entity
//#Table(name="users")
public class User {
#Id
private int id;
private String name;
private int total;
private int goal;
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 int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getGoal() {
return goal;
}
public void setGoal(int goal) {
this.goal = goal;
}
}
If I uncomment the #Table annotation from the user class, the app looks for the correct (users) table. Why the xml configuration is not working?
Bellow you can see the hibernate helper class, and my main()
HibernateUtilities.java
public class HibernateUtilities {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
static {
try {
Configuration conf = new Configuration().configure();
conf.addAnnotatedClass(com.andrei.User.class);
conf.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
sessionFactory = conf.buildSessionFactory(serviceRegistry);
} catch (HibernateException e) {
System.out.println("problem creating session factory: " + e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Main.java
public static void main(String[] args) {
Session session = HibernateUtilities.getSessionFactory().openSession();
session.beginTransaction();
User user = new User();
user.setName("first name");
user.setGoal(250);
session.save(user);
session.getTransaction().commit();
session.close();
HibernateUtilities.getSessionFactory().close();
}
Here are my questions
Why the xml configuration does not work? The table name specified in user.hbm.xml is users, but the app looks for table user.
Why <property name="hibernate.hbm2ddl.auto">create</property> does not work?
Here are my logs:
Hibernate: drop table if exists users Dec 26, 2017 4:55:42 PM
org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl
getIsolatedConnection INFO: HHH10001501: Connection obtained from
JdbcConnectionAccess
[org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#4612b856]
for (non-JTA) DDL execution was not in auto-commit mode; the
Connection 'local transaction' will be committed and the Connection
will be set into auto-commit mode. Hibernate: create table users (id
integer not null, goal integer not null, name varchar(255), total
integer not null, primary key (id)) type=MyISAM Dec 26, 2017 4:55:42
PM
org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl
getIsolatedConnection INFO: HHH10001501: Connection obtained from
JdbcConnectionAccess
[org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#74eb909f]
for (non-JTA) DDL execution was not in auto-commit mode; the
Connection 'local transaction' will be committed and the Connection
will be set into auto-commit mode. Dec 26, 2017 4:55:42 PM
org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl
handleException WARN: GenerationTarget encountered exception accepting
command : Error executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error
executing DDL via JDBC Statement at
org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at
org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440)
at
org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424)
at
org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:315)
at
org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166)
at
org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135)
at
org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121)
at
org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155)
at
org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
at
org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:313)
at
org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at com.andrei.HibernateUtilities.(HibernateUtilities.java:21)
at com.andrei.Program.main(Program.java:8) Caused by:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'type=MyISAM' at
line 1 at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) at
com.mysql.jdbc.Util.getInstance(Util.java:408) at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) at
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) at
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2480) at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2438) at
com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:845)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:745) at
org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
... 13 more
Dec 26, 2017 4:55:42 PM
org.hibernate.tool.schema.internal.SchemaCreatorImpl
applyImportSources INFO: HHH000476: Executing import script
'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#2826f61'
Hibernate: insert into users (goal, name, total, id) values (?, ?, ?,
?) Dec 26, 2017 4:55:42 PM
org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN:
SQL Error: 1146, SQLState: 42S02 Dec 26, 2017 4:55:42 PM
org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR:
Table 'protein_tracker.users' doesn't exist Dec 26, 2017 4:55:42 PM
org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC
statements Dec 26, 2017 4:55:42 PM
org.hibernate.internal.ExceptionMapperStandardImpl
mapManagedFlushFailure ERROR: HHH000346: Error during managed flush
[org.hibernate.exception.SQLGrammarException: could not execute
statement] Exception in thread "main"
javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: could not execute
statement at
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149)
at
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1443)
at
org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:493)
at
org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3207)
at
org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2413)
at
org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:473)
at
org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:156)
at
org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at
org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
at
org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at com.andrei.Program.main(Program.java:17) Caused by:
org.hibernate.exception.SQLGrammarException: could not execute
statement at
org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
at
org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3013)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3513)
at
org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:589)
at
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at
org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at
org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1437)
... 9 more Caused by:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table
'protein_tracker.users' doesn't exist at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) at
com.mysql.jdbc.Util.getInstance(Util.java:408) at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) at
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) at
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2484) at
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at
com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
at
com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
at
com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
at
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
... 18 more
One of the lines above:
Hibernate: create table users (id integer not null, goal integer not null, name varchar(255), total integer not null, primary key (id)) type=MyISAM
but after this, there is an exception which I don't understand. In mySql, there is no table created.
Thank you very much and a happy new year!
I am not sure, just follow documentation Hibernate_doc
Configuration cfg = new Configuration()
.addClass(com.andrei.User.class)
in this case hibernate will be search configuration for this class User.hbm.xml. Pay attention the config files should be placed near declared class.
instead of
conf.addAnnotatedClass(com.andrei.User.class);
About second question. Where do you situated the configuration file hibernate.cfg.xml ??
You should use (or implement) custom NamingStrategy class in order to map classname "User" to tablename "Users. See for details spring - hibernate 5 naming strategy 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

Mapping (RESOURCE) not found

Guys I am new with Hibernate and I am struggling to make a hello world app work. Below I will post the exception I am getting as well as my code - with the hope maybe someone can spot other errors which I have and save me from "future" troubles.
Code:
package org.arpit.javapostsforlearning;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity(name = "User_table")
public class User {
#Id
int userId;
#Column(name = "User_Name")
String userName;
String userMessage;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserMessage() {
return userMessage;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
}
This:
package org.arpit.javapostsforlearning;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateMain {
public static void main(String[] args)
{
Configuration configuration=new Configuration();
configuration.configure();
configuration.addClass(org.arpit.javapostsforlearning.User.class);
ServiceRegistry sr= new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sf=configuration.buildSessionFactory(sr);
User user1=new User();
user1.setUserName("Arpit");
user1.setUserMessage("Hello world from arpit");
User user2=new User();
user2.setUserName("Ankita");
user2.setUserMessage("Hello world from ankita");
Session ss=sf.openSession();
ss.beginTransaction(); //saving objects to session
ss.save(user1);
ss.save(user2);
ss.getTransaction().commit();
ss.close();
}
}
And XMLS:
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://localhost:1433;database=Sandboxlearning;integratedSecurity=true</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</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>
<mapping class="User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
User.hbm.xml
<?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="User" table="User_table">
<meta attribute="class-description">
This class contains the user detail.
</meta>
<id name="userId" type="int" column="userId">
<generator class="native"/>
</id>
<property name="userName" column="User_Name" type="string"/>
<property name="userMessage" column="userMessage" type="string"/>
</class>
</hibernate-mapping>
Exception:
Jun 28, 2016 7:17:15 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.0.Final}
Jun 28, 2016 7:17:15 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 28, 2016 7:17:15 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jun 28, 2016 7:17:15 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Exception in thread "main" org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not found : org/arpit/javapostsforlearning/User.hbm.xml : origin(org/arpit/javapostsforlearning/User.hbm.xml)
at org.hibernate.boot.spi.XmlMappingBinderAccess.bind(XmlMappingBinderAccess.java:56)
at org.hibernate.boot.MetadataSources.addResource(MetadataSources.java:274)
at org.hibernate.boot.MetadataSources.addClass(MetadataSources.java:262)
at org.hibernate.cfg.Configuration.addClass(Configuration.java:513)
at org.arpit.javapostsforlearning.HibernateMain.main(HibernateMain.java:14)
The XMLS are stored under src folder.
Here is also screen shot of my App
image
Take a look to: <mapping class="User.hbm.xml"/>. But you using resource. You are able to use class when you saying that map me class for that, but you want to map resource. So just use
<mapping resource="User.hbm.xml"/>

Hibernate returns duplicate values if result size is greater than 1

I have a simple table in PostgreSQL called "transaction_response". In this table, there are only two columns: transaction_id and response_id.
The data I have in there are two rows. Both with the same transaction_id, but different response_id values.
I created the following Java class to hold this data:
public class TransactionResponseDAO implements java.io.Serializable {
private Integer transactionId;
private Integer responseId;
public Integer getTransactionId() {
return transactionId;
}
public void setTransactionId(Integer transactionId) {
this.transactionId = transactionId;
}
public Integer getResponseId() {
return responseId;
}
public void setResponseId(Integer responseId) {
this.responseId = responseId;
}
public String toString() {
return "Transaction Id: " + transactionId + "\nResponse Id: " + responseId;
}
}
I then created the Hibernate config file called "TransactionResponse.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.data.TransactionResponseDAO" table="transaction_response">
<id name="transactionId" column="transaction_id" type="java.lang.Integer">
<generator class="increment"/>
</id>
<property name="responseId" type="java.lang.Integer">
<column name="responses_id" />
</property>
</class>
<query name="findTransactionResponseByTransactionId">
<![CDATA[from com.data.TransactionResponseDAO where transaction_id = :transactionId]]>
</query>
<query name="findTransactionResponseByBothIds">
<![CDATA[from com.data.TransactionResponseDAO where transaction_id = :transactionId
and responses_id = :responseId]]>
</query>
</hibernate-mapping>
In a Java class I am testing this with, I have the following code:
Query q = null;
SessionFactory sFactory = new Configuration().configure("/conf/hibernate.cfg.xml").buildSessionFactory();
Session session = null;
try {
session = sFactory.openSession();
q = session.getNamedQuery("findTransactionResponseByTransactionId");
q.setInteger("transactionId", transactionId);
}catch (Exception e) {
System.err.println("Error running getStatusTab");
e.printStackTrace();
session.close();
sFactory.close();
}
ArrayList<TransactionResponseDAO> results = (ArrayList<TransactionResponseDAO>) q.list();
session.close();
sFactory.close();
System.out.println(">>> Size: " + results.size());
for (TransactionResponseDAO tr : results) {
System.out.println(tr);
System.out.println();
}
When I run this code, it returns two rows back, as it should. However, when printing out the values... the response_id is the same for both rows. So it doesn't seem to be pulling in the second response_id value for some reason.
Any reason why this is? As always, I appreciate the help!
The problem is the cache mechanism of hibernate. When hibernate fetchs the first row and create a object, it caches that object by the indicated id column (transactionId). When hibernate fetchs the second row, it thinks that is the same row as the first one, because those rows have the same id, get the object from the cache (the same object) and put it again on the result.
If the colum transactionId is not unique, don't map it with id tag.
Thank you for the feedback. What I did was use a composite_id instead and that fixed it. Thanks again!
<?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.data.TransactionResponseDAO" table="transaction_response">
<composite-id name="primaryKey" class="com.data.TransactionResponsePK">
<key-property name="transactionId" column="transaction_id" type="java.lang.Integer" />
<key-property name="responseId" column="responses_id" type="java.lang.Integer" />
</composite-id>
</class>
<query name="findTransactionResponseByTransactionId">
<![CDATA[from com.data.TransactionResponseDAO tr where tr.primaryKey.transactionId = :transactionId]]>
</query>
<query name="findTransactionResponseByBothIds">
<![CDATA[from com.data.TransactionResponseDAO tr where tr.primaryKey.transactionId = :transactionId
and tr.primaryKey.responseId = :responseId]]>
</query>
</hibernate-mapping>

Categories

Resources