Java - Hibernate connection database - java

I'am learning to use java since few weeks et i want to use Hibernate in simple Java console application.
I download the last version of Hibernate ORM (4.3.8)
I add this Jars in my ClassPath :
com.mysql.jdbc_5.1.5.jar
sqlite-jdbc-3.8.7.jar
Hibernate Library\antlr-2.7.7.jar
Hibernate Library\dom4j-1.6.1.jar
Hibernate Library\hibernate-commons-annotations-4.0.5.Final.jar
Hibernate Library\hibernate-core-4.3.8.Final.jar
Hibernate Library\hibernate-jpa-2.1-api-1.0.0.Final.jar
Hibernate Library\jandex-1.1.0.Final.jar
Hibernate Library\javassist-3.18.1-GA.jar
Hibernate Library\jboss-logging-3.1.3.GA.jar
Hibernate Library\jboss-logging-annotations-1.2.0.Beta1.jar
Hibernate Library\jboss-transaction-api_1.2_spec-1.0.0.Final.jar
My Class :
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENT_INFORMATIONS")
public class Student_Info {
#Id
private int rollNo;
private String name;
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My Main Code :
Student_Info student = new Student_Info();
student.setName("Fabien");
student.setRollNo(1);
SessionFactory sessionFactory;
ServiceRegistry serviceRegistry;
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(student);
session.getTransaction().commit();
session.close();
sessionFactory.close();
SQLite
First i create an hibernate.cfg.xml configuration for SQLite with dialect property to "util.SQLiteDialect"
<?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="show_sql">true</property>
<property name="format_sql">true</property>
<property name="dialect">util.SQLiteDialect</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="connection.url">jdbc:sqlite:SQLiteJDBC.sqlite</property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<!-- create / update -->
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- Liste des classes à Mapper en base de données -->
<!-- <mapping resource="User.hbm.xml"/> -->
<mapping class="com.hibernate.Student_Info"/>
</session-factory>
</hibernate-configuration>
When i run my main program i have this error :
...
INFO: HHH000006: Autocommit mode: false
janv. 10, 2015 4:23:40 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Exception in thread "main" org.hibernate.boot.registry.selector.spi.StrategySele
ctionException: Unable to resolve name [util.SQLiteDialect] as strategy [org.hib
ernate.dialect.Dialect]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStr
ategyImplementor(StrategySelectorImpl.java:128)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDe
faultableStrategy(StrategySelectorImpl.java:155)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveSt
rategy(StrategySelectorImpl.java:136)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDiale
ct(DialectFactoryImpl.java:78)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(D
ialectFactoryImpl.java:68)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesIm
pl.java:165)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureSe
rvice(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService
(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(Abstra
ctServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:18
87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at com.hibernate.Main.main(Main.java:26)
MySql
After i tried with a mysql Database
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hierbnate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<!-- JDBC Connection pool -->
<property name="connection.pool_size">1</property>
<!-- SQL Dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_cass">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- create / update -->
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- Liste des classes à Mapper en base de données -->
<!-- <mapping resource="User.hbm.xml"/> -->
<mapping class="com.hibernate.Student_Info"/>
</session-factory>
</hibernate-configuration>
When i run my main programm i have this error :
...
janv. 10, 2015 4:41:43 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://local
host:3306/hierbnate]
janv. 10, 2015 4:41:43 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
janv. 10, 2015 4:41:43 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
janv. 10, 2015 4:41:43 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Error ca
lling Driver#connect
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLState
ConversionDelegate.java:123)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.co
nvert(BasicConnectionCreator.java:118)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.conver
tSqlException(BasicConnectionCreator.java:140)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeC
onnection(DriverConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.create
Connection(BasicConnectionCreator.java:75)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProvid
erImpl.configure(DriverManagerConnectionProviderImpl.java:106)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureSe
rvice(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService
(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(Abstra
ctServiceRegistryImpl.java:206)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAcces
s(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesIm
pl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureSe
rvice(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService
(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(Abstra
ctServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:18
87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at com.hibernate.Main.main(Main.java:25)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown da
tabase 'hierbnate'
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:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1031)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:894)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3808)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1256)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2032)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
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:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeC
onnection(DriverConnectionCreator.java:55)
... 13 more
1 - Do you know if is it possible to use hibernate on SQLite ?
2 - If yes, do you know why it doesn't works ?
3 - For MySql, what is the problem ?
thank you very much !!

Thanks to Todd for my Syntaxe Error (MySql).
For SQLite, the dialect is not present in hibernate 4.3. So i found and adapt a classe for use SQLite with Hibernate 4.3.8 :
/*
* The author disclaims copyright to this source code. In place of
* a legal notice, here is a blessing:
*
* May you do good and not evil.
* May you find forgiveness for yourself and forgive others.
* May you share freely, never taking more than you give.
*
*/
package org.hibernate.dialect;
import java.sql.Types;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.Hibernate;
public class SQLiteDialect extends Dialect {
public SQLiteDialect() {
registerColumnType(Types.BIT, "integer");
registerColumnType(Types.TINYINT, "tinyint");
registerColumnType(Types.SMALLINT, "smallint");
registerColumnType(Types.INTEGER, "integer");
registerColumnType(Types.BIGINT, "bigint");
registerColumnType(Types.FLOAT, "float");
registerColumnType(Types.REAL, "real");
registerColumnType(Types.DOUBLE, "double");
registerColumnType(Types.NUMERIC, "numeric");
registerColumnType(Types.DECIMAL, "decimal");
registerColumnType(Types.CHAR, "char");
registerColumnType(Types.VARCHAR, "varchar");
registerColumnType(Types.LONGVARCHAR, "longvarchar");
registerColumnType(Types.DATE, "date");
registerColumnType(Types.TIME, "time");
registerColumnType(Types.TIMESTAMP, "timestamp");
registerColumnType(Types.BINARY, "blob");
registerColumnType(Types.VARBINARY, "blob");
registerColumnType(Types.LONGVARBINARY, "blob");
// registerColumnType(Types.NULL, "null");
registerColumnType(Types.BLOB, "blob");
registerColumnType(Types.CLOB, "clob");
registerColumnType(Types.BOOLEAN, "integer");
registerFunction( "concat", new VarArgsSQLFunction(StringType.INSTANCE, "", "||", "") );
registerFunction( "mod", new SQLFunctionTemplate( IntegerType.INSTANCE, "?1 % ?2" ) );
registerFunction( "substr", new StandardSQLFunction("substr", StringType.INSTANCE) );
registerFunction( "substring", new StandardSQLFunction( "substr", StringType.INSTANCE ) );
}
public boolean supportsIdentityColumns() {
return true;
}
/*
public boolean supportsInsertSelectIdentity() {
return true; // As specify in NHibernate dialect
}
*/
public boolean hasDataTypeInIdentityColumn() {
return false; // As specify in NHibernate dialect
}
/*
public String appendIdentitySelectToInsert(String insertString) {
return new StringBuffer(insertString.length()+30). // As specify in NHibernate dialect
append(insertString).
append("; ").append(getIdentitySelectString()).
toString();
}
*/
public String getIdentityColumnString() {
// return "integer primary key autoincrement";
return "integer";
}
public String getIdentitySelectString() {
return "select last_insert_rowid()";
}
public boolean supportsLimit() {
return true;
}
protected String getLimitString(String query, boolean hasOffset) {
return new StringBuffer(query.length()+20).
append(query).
append(hasOffset ? " limit ? offset ?" : " limit ?").
toString();
}
public boolean supportsTemporaryTables() {
return true;
}
public String getCreateTemporaryTableString() {
return "create temporary table if not exists";
}
public boolean dropTemporaryTableAfterUse() {
return false;
}
public boolean supportsCurrentTimestampSelection() {
return true;
}
public boolean isCurrentTimestampSelectStringCallable() {
return false;
}
public String getCurrentTimestampSelectString() {
return "select current_timestamp";
}
public boolean supportsUnionAll() {
return true;
}
public boolean hasAlterTable() {
return false; // As specify in NHibernate dialect
}
public boolean dropConstraints() {
return false;
}
public String getAddColumnString() {
return "add column";
}
public String getForUpdateString() {
return "";
}
public boolean supportsOuterJoinForUpdate() {
return false;
}
public String getDropForeignKeyString() {
throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect");
}
public String getAddForeignKeyConstraintString(String constraintName,
String[] foreignKey, String referencedTable, String[] primaryKey,
boolean referencesPrimaryKey) {
throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect");
}
public String getAddPrimaryKeyConstraintString(String constraintName) {
throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect");
}
public boolean supportsIfExistsBeforeTableName() {
return true;
}
public boolean supportsCascadeDelete() {
return false;
}
#Override
public boolean bindLimitParametersInReverseOrder() {
return true;
}
}

I think you might have just spelled "hibernate" wrong...
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'hierbnate'
Try changing this:
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hierbnate</property>
To this:
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
(Unless your db is really called hierbnate, and then I'll just delete this answer).

Related

Exception in Hibernate Configuration [duplicate]

This question already has answers here:
TNS-12505: TNS:listener does not currently know of SID given in connect descriptor
(17 answers)
Closed 5 years ago.
I am very new to Spring, Hibernate. while working on hibernate I am facing the following problem. I also searched related tags on stackoverflow, but couldn't found any relevant post that solved my issues.
Student.java File
package hibernatepractise;
public class Student {
private long id;
private String name;
private String degree;
private String phone;
public Student() {
super();
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getDegree() {
return degree;
}
public String getPhone() {
return phone;
}
public void setId(long String) {
id = String;
}
public void setName(String string) {
name = string;
}
public void setDegree(String string) {
degree = string;
}
public void setPhone(String string) {
phone = string;
}
public String toString() {
return name;
}
}
AddStudent.java File
package hibernatepractise;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import hibernatepractise.Student;
public class AddStudent {
private static SessionFactory sessionFactory;
public static void main(String args[]) throws Exception {
// begin if
// A
String name = "Jayesh Vyas";
String degree = "B.tech Completed";
String phone = "9421345678";
System.out.println("Name: " + name);
System.out.println("Degree: " + degree);
System.out.println("Phone: " + phone);
if ((name.equals("") || degree.equals("") || phone.equals(""))) {
System.out.println("All informations are Required");
} else {
try {// begin try
sessionFactory = new Configuration().configure("/hibernate.cfg.xml").buildSessionFactory();
// sessionFactory1 = new
// Configuration().configure("com\\xml\\student1.cfg.xml").buildSessionFactory();
} catch (Exception e) {
System.out.println("mathan");
System.out.println(e.getMessage());
System.err.println("Initial SessionFactory creation failed."+ e);
}
Session s = sessionFactory.openSession();
// Session s1 =sessionFactory1.openSession();
// Transaction tx1= s1.beginTransaction();
Transaction tx = s.beginTransaction();
Student stu = new Student();
stu.setName(name);
stu.setDegree(degree);
stu.setPhone(phone);
s.save(stu);
tx.commit();
System.out.println("Added to oracle Database");
if (s != null)
s.close();
// Student1 stu1=new Student1();
// stu1.setName(name1);
// s1.save(stu1);
// tx1.commit();
// System.out.println("Added to mysql Database");
// if (s1 != null)
// s1.close();
}
// }// end of if A
}// end of method
}// end of class
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="studentFactory">
<property name="connection.driver_class">
oracle.jdbc.OracleDriver
</property>
<property name="connection.url">
jdbc:oracle:thin:#localhost:1521:test
</property>
<property name="connection.username">
system
</property>
<property name="connection.password">
manager
</property>
<property name="connection.pool_size">5</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.OracleDialect
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Student.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="hibernatepractise.Student" table="studentOracle1">
<id name="id" type="long" column="ID">
<generator class="increment" />
</id>
<property name="name" column="name" not-null="true" />
<property name="degree" column="degree" />
<property name="phone" column="phone" />
</class>
</hibernate-mapping>
I am facing the following errors in my code
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
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:420)
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 hibernatepractise.AddStudent.main(AddStudent.java:42)
Caused by: java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:480)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:413)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:508)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:203)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510)
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:417)
... 5 more
Caused by: oracle.net.ns.NetException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:361)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:966)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:292)
... 13 more
I know that there is a silly mistake in my code but I am not able to find out as I am new to hibernate so that's why i request you to please help me to get out from this problem.
I shall be highly thankful to you for this.
Thanks in Advance.
I believe the error lies in this line:
jdbc:oracle:thin:#localhost:1521:test. I think it should be
jdbc:oracle:thin:#localhost:1521/test
A / instead of a :

Unable to Load Mapper Class in Hibernate

I'm very new to Hibernate. Followed by a youtube tutorial, I created a hibernate program but getting an error. Please find the Class and the error below. Solution for this will be highly grateful.
Error:
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Oct 29, 2016 4:36:53 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Oct 29, 2016 4:36:53 AM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Exception in thread "main" org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [Emp.hbm.xml]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:229)
at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.<init>(AnnotationMetadataSourceProcessorImpl.java:104)
Main Function()
public static void main( String[ ] args ) throws ParseException {
Configuration cfg = new Configuration();
cfg.configure("Hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
String name2 = "yahoo";
LoginRegister lr = new LoginRegister();
lr.set_username(name2.toLowerCase()+"_user");
lr.set_password(name2.toLowerCase()+"_pass");
lr.set_last_update(new java.sql.Date(new SimpleDateFormat("yyyyMMdd").parse("20110210").getTime()));
s.save(lr);
s.flush();
tx.commit();
s.close();
}
POJO CLASS:
package dto;
import java.io.Serializable;
import java.sql.Date;
public class LoginRegister implements Serializable{
private int _id;
private String _username = null;
private String _password = null;
Date _last_update = null;
public LoginRegister(){}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_username() {
return _username;
}
public void set_username(String _username) {
this._username = _username;
}
public String get_password() {
return _password;
}
public void set_password(String _password) {
this._password = _password;
}
public Date get_last_update() {
return _last_update;
}
public void set_last_update(Date _last_update) {
this._last_update = _last_update;
}
public String toString(){
return
"Id : "+this._id+"\n"+
"Username : "+this._username+"\n"+
"Password : "+this._password+"\n"+
"Last Update : "+this._last_update;
}
}
Configuration File :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database Connection -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- Driver -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Language Used (Dialect) : Here SQL -->
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property><!-- URL -->
<property name="connection.username">root</property> <!-- Username -->
<property name="connection.password"></property> <!-- Password -->
<!-- To generate SQL Queries when running the program -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<!-- For JDBC Transaction -->
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- Auto Commit -->
<property name="hibernate.connection.autocommit">false</property>
<!-- Mapping Class -->
<mapping class ="Emp.hbm.xml" />
</session-factory>
</hibernate-configuration>
Entity Mapper File:
<?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="qqqLoginRegister" table="qqqlogin_register">
<id name="_id" column="id" type="integer">
<generator class="assigned"/>
</id>
<property name="_userName" column="username" type="string"/>
<property name="_password" column="password" type="string"/>
<property name="_last_update" column="last_update" type="date"/>
</class>
</hibernate-mapping>
Locations :
Configuration FIle : srs\Hibernate.cfg.xml
Entity Mapper : src\Emp.hbm.xml
POJO : src\dto\LoginRegister.java
Main Class : src\dao\Index.java
As you are NOT using the Hibernate bean annoatations, in your Hibernate.cfg.xml file, you need to change <mapping class ="Emp.hbm.xml" /> to <mapping resource ="Emp.hbm.xml" />
Hibernate is an ORM framework which maps the Java Bean to a Relational database table and the mapping can be provided directly in the Java Bean Object (using Annotations) or can be provided separately through xml files (like how you did).
Hibernate SessionFactory mappings are compiled from various XML mapping files and <mapping resource is used to load those mapping files (in your case it is a single file which is Emp.hbm.xml file)
You can refer the below documentation for more details:
https://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

hibernate with lucene search index files are not created: IndexWriterConfig.setWriteLockTimeout(J)Lorg/apache/lucene/index/IndexWriterConfig;

I have a small project that I want to integrate with lucene and hibernate:
This is the bean file:
package com.domain.java;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.search.annotations.Analyzer;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
#Entity
#Indexed
#Analyzer(impl = org.apache.lucene.analysis.standard.StandardAnalyzer.class)
public class TempFile {
#Field(store = Store.YES)
private String iconName;
#Field(store = Store.YES)
private String name;
#Id
#DocumentId
#Field(store = Store.YES)
private String path;
#Field(store = Store.YES)
private boolean mightHaveThumbnail;
#Field(store = Store.YES)
private boolean folder;
#Field(store = Store.YES)
private boolean file;
public String getIconName() {
return iconName;
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
public boolean isMightHaveThumbnail() {
return mightHaveThumbnail;
}
public boolean isFolder() {
return folder;
}
public boolean isFile() {
return file;
}
public void setIconName(String iconName) {
this.iconName = iconName;
}
public void setName(String name) {
this.name = name;
}
public void setPath(String path) {
this.path = path;
}
public void setMightHaveThumbnail(boolean mightHaveThumbnail) {
this.mightHaveThumbnail = mightHaveThumbnail;
}
public void setFolder(boolean folder) {
this.folder = folder;
}
public void setFile(boolean file) {
this.file = file;
}
}
And this the Hibernate file:
package com.domain.java;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.service.ServiceRegistry;
public class HibernateTest {
public static void main(String[] args) {
TempFile mm = new TempFile();
mm.setFile(true);
mm.setPath("patdsaasdsadahswdsaaad "+new Date());
mm.setName("nasdasassadasaeeassaaasddas "+new Date());
Properties properties = new Properties();
try {
properties.load(new FileInputStream("./resources/postgres/hibernate.properties"));
// readAPropertyFile("./resources/postgres/hibernate.properties");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Configuration configuration = new Configuration();
File file = new File("./resources/postgres/hibernate.cfg.xml");
System.out.println(file.exists());
configuration.mergeProperties(properties);
configuration.configure(file);
configuration.addAnnotatedClass(TempFile.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
FullTextSession fullTextSession = Search.getFullTextSession(session);
try {
fullTextSession.createIndexer().startAndWait();
fullTextSession.beginTransaction();
fullTextSession.close();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// session.save(mm);
// session.getTransaction().commit();
session.close();
// now lets pull events from the database and list them
session = sessionFactory.openSession();
session.beginTransaction();
List result = session.createQuery("from TempFile").list();
for ( TempFile event : (List<TempFile>) result ) {
System.out.println( "Event (" + event.getPath() + ") : " + event.getPath() );
System.out.println( "Event (" + event.getName() + ") : " + event.getName() );
}
session.getTransaction().commit();
session.close();
}
private static void readAPropertyFile(String propertiesFilePath) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(propertiesFilePath);
// load a properties file
prop.load(input);
// get the property value and print it out
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = prop.getProperty(key);
System.out.println("Key : " + key + ", Value : " + value);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
The configuration files:
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<!-- <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost/TestDB</property> -->
<!-- Echo all executed SQL to stdout -->
<!-- >property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hibernate.search.default.directory_provider">filesystem</property>
-->
<!--
< Enable Hibernate's automatic session context management >
<property name="current_session_context_class">thread</property>
<property name="cache.use_query_cache">true</property>
<property name="cache.use_second_level_cache">true</property>
<property name="cache.use_structured_entries">true</property>
<property name="cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>
<property name="net.sf.ehcache.configurationResourceName">/hibernate-config/ehcache.xml</property>
mapping resource="hibernate-config/domain/Event.hbm.xml"/>
<mapping resource="hibernate-config/domain/Person.hbm.xml"/>
<mapping resource="hibernate-config/domain/PhoneNumber.hbm.xml"/>
<mapping resource="hibernate-config/domain/Account.hbm.xml"/>
<mapping resource="hibernate-config/domain/HolidayCalendar.hbm.xml"/>
<mapping resource="hibernate-config/domain/Item.hbm.xml"/-->
<!--
<mapping class="com.domain.java.TempFile"/>
org.hibernate.search.store.impl.RAMDirectoryProvider
-->
<!-- Would set this in production application. Index stored on disk. -->
<property name="hibernate.search.default.directory_provider">
org.hibernate.search.store.impl.FSDirectoryProvider
</property>
<property name="hibernate.search.default.indexBase">c:\aatemp\lucene\indexes</property>
</session-factory>
</hibernate-configuration>
The property file
######################
### Query Language ###
######################
## define query language constants / function names
hibernate.query.substitutions yes 'Y', no 'N'
## select the classic query parser
#hibernate.query.factory_class org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory
#################
### Platforms ###
#################
## JNDI Datasource
#hibernate.connection.datasource jdbc/test
#hibernate.connection.username db2
#hibernate.connection.password db2
## PostgreSQL
hibernate.dialect org.hibernate.dialect.PostgreSQLDialect
hibernate.connection.driver_class org.postgresql.Driver
hibernate.connection.url jdbc:postgresql://localhost:5432/hibernatedb
hibernate.connection.username postgres
hibernate.connection.password xxxxxxxx
hibernate.hbm2ddl.auto=update
show_sql=true
#Lucene
hibernate.search.default.directory_provider filesystem
hibernate.search.default.indexBase c:/var/lucene/indexes
hibernate.search.default.locking_strategy simple
I am getting following exception running the above code:
May 27, 2016 6:39:19 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
May 27, 2016 6:39:19 AM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
May 27, 2016 6:39:19 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
true
May 27, 2016 6:39:19 AM 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.
May 27, 2016 6:39:19 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator
instantiateProxoolProvider
WARN: HHH000209: proxool properties were encountered, but the proxool provider class was not found on the classpath; these
properties are going to be ignored.
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/hibernatedb]
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
buildCreator
INFO: HHH10001003: Autocommit mode: false
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
May 27, 2016 6:39:19 AM org.hibernate.dialect.Dialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
May 27, 2016 6:39:19 AM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl
useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
May 27, 2016 6:39:19 AM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#10aa41f2
May 27, 2016 6:39:19 AM org.hibernate.envers.boot.internal.EnversServiceImpl configure
INFO: Envers integration enabled? : true
May 27, 2016 6:39:20 AM org.hibernate.search.engine.Version
INFO: HSEARCH000034: Hibernate Search 5.5.2.Final
May 27, 2016 6:39:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:postgresql://localhost:5432/hibernatedb]
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.lucene.index.IndexWriterConfig.setWriteLockTimeout(J)Lorg/apache/lucene/index/IndexWriterConfig;
at org.hibernate.search.store.spi.DirectoryHelper.initializeIndexIfNeeded(DirectoryHelper.java:57)
at org.hibernate.search.store.impl.DirectoryProviderHelper.createFSIndex(DirectoryProviderHelper.java:128)
at org.hibernate.search.store.impl.FSDirectoryProvider.initialize(FSDirectoryProvider.java:53)
at org.hibernate.search.store.spi.BaseDirectoryProviderService.initialize(BaseDirectoryProviderService.java:64)
at org.hibernate.search.store.spi.BaseDirectoryProviderService.create(BaseDirectoryProviderService.java:52)
at org.hibernate.search.indexes.spi.DirectoryBasedIndexManager.createDirectoryProvider(DirectoryBasedIndexManager.java:230)
at org.hibernate.search.indexes.spi.DirectoryBasedIndexManager.initialize(DirectoryBasedIndexManager.java:90)
at org.hibernate.search.indexes.impl.IndexManagerHolder.createIndexManager(IndexManagerHolder.java:256)
at org.hibernate.search.indexes.impl.IndexManagerHolder.createIndexManager(IndexManagerHolder.java:513)
at org.hibernate.search.indexes.impl.IndexManagerHolder.createIndexManagers(IndexManagerHolder.java:482)
at org.hibernate.search.indexes.impl.IndexManagerHolder.buildEntityIndexBinding(IndexManagerHolder.java:91)
at org.hibernate.search.spi.SearchIntegratorBuilder.initDocumentBuilders(SearchIntegratorBuilder.java:358)
at org.hibernate.search.spi.SearchIntegratorBuilder.buildNewSearchFactory(SearchIntegratorBuilder.java:199)
at org.hibernate.search.spi.SearchIntegratorBuilder.buildSearchIntegrator(SearchIntegratorBuilder.java:117)
at org.hibernate.search.hcore.impl.HibernateSearchSessionFactoryObserver.sessionFactoryCreated(HibernateSearchSessionFactoryObserver.java:75)
at org.hibernate.internal.SessionFactoryObserverChain.sessionFactoryCreated(SessionFactoryObserverChain.java:35)
at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:520)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at com.domain.java.HibernateTest.main(HibernateTest.java:48)
The com.domain.java.TempFile folder is created at the lucene index path but the folder is empty and the above exception is trowed.
The real problem is here:
org.apache.lucene.index.IndexWriterConfig.setWriteLockTimeout(J)Lorg/apache/lucene/index/IndexWriterConfig;
You have a dependency issue: the Lucene version you are using is not compatible with the version of Hibernate Search you're using.
Check your dependencies and fix them and your issue should go away.

Hibernate 5.1.0 Errors Unable to perform unmarshalling and Cannot find the declaration of element 'hibernate-configuration'

Trying to create a simple student database with a single entry in it.
I am using Hibernate 5.1.0 and MySql as database with simple student table, and cannot connect to the database. Using Eclipse Mars and also MYSQL jdbc driver added to the project along with hibernate 5.1 necessary jars.
My StudentInfo.java file
package com.nitish.hibernate;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class StudentInfo {
#Id
private int rollno;
private String name;
private int marks;
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
}
my Main.java File
package com.nitish.hibernate;
import org.hibernate.*;
public class Main {
public static void main(String args[]){
StudentInfo s1 = new StudentInfo();
s1.setName("Nitishpisal");
s1.setRollno(5);
s1.setMarks(33);
try{
Configuration conf = new Configuration();
System.out.println("Hibernate Configuration loaded");
conf.configure("hibernate.cfg.xml");
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
System.out.println("registry loaded");
SessionFactory sf = conf.buildSessionFactory(sr);
System.out.println(" session factory loaded");
Session session = sf.openSession();
session.beginTransaction();
session.save(s1);
session.getTransaction().commit();
}catch(HibernateException e){
e.printStackTrace();
}
}
}
My hibernate.cfg.xml file
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration xmlns="http://www.hibernate.org/xsd/hibernate-configuration">
<session-factory>
<!-- Database connection settings --> -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<!-- model classes and mapping info-->
<mapping class="com.nitish.hibernate.StudentInfo"></property>
</session-factory>
</hibernate-configuration>
The error I am getting
May 23, 2016 2:16:51 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 23, 2016 2:16:51 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Hibernate Configuration loaded
May 23, 2016 2:16:51 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.
org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 5 and column 87 in RESOURCE hibernate.cfg.xml. Message: cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
at org.hibernate.cfg.Configuration.configure(Configuration.java:259)
at com.nitish.hibernate.Main.main(Main.java:27)
Caused by: javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 87; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:468)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:448)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:420)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:126)
... 5 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 87; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1906)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:746)
at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.startElement(ValidatorHandlerImpl.java:570)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(ValidatingUnmarshaller.java:86)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(InterningXmlVisitor.java:60)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.handleStartElement(StAXEventConnector.java:246)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(StAXEventConnector.java:115)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:445)
... 7 more
any help will be highly appreciated!
Try to remove this string:
xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
Remove closing property tag after declaration of mapping class in hibernate.cfg.xml
Replace
<!-- model classes and mapping info-->
<mapping class="com.nitish.hibernate.StudentInfo"></property>
with
<!-- model classes and mapping info-->
<mapping class="com.nitish.hibernate.StudentInfo">

Is it possible to get two output parameters from stored T-SQL procedure using Hibernate 4?

I new in hibernate.
I need to call MS SQL 2008 procedure using Hibernate 4 and print results to console.
Proc:
CREATE PROCEDURE [dbo].[PRODUCT_CREATE](
#ReturnValue INT output,
#ProductID INT output,
#PassID numeric(18,0),
#Amount numeric(18,2))
as
BEGIN
print 'PassID = ' + convert(varchar, #PassID);
print 'Amount = ' + convert(varchar, #Amount);
select #ReturnValue = 999999,
#ProductID = 777777;
END;
Mapping:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<sql-query name="PRODUCT_CREATE" callable="true">
<return-scalar column = "retVal" type="int"/>
<return-scalar column = "cardId" type="int"/>
<![CDATA[{CALL PRODUCT_CREATE (:ReturnValue,
:ProductID,
:PassID,
:Amount
)}]]>
</sql-query>
</hibernate-mapping>
Main class:
package app;
import java.math.BigInteger;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
public class App {
public static void main(String[] args) {
App.createProduct();
}
public static BigInteger createProduct()
{
/**
* Open session and begin database transaction for database operation.
*/
SessionFactory sf = HibernateUtil.createSessionFactory();
Session session = sf.openSession();
Query qr = session.getNamedQuery("PRODUCT_CREATE");
qr.setParameter("ReturnValue", 0);
qr.setParameter("ProductID", 0);
qr.setParameter("PassID", new BigInteger("1000999"));
qr.setParameter("Amount", new BigInteger("1000001"));
#SuppressWarnings("unchecked")
/*The problem is here*/
List<ProductModel> list = qr.setResultTransformer(Transformers.aliasToBean(ProductModel.class)).list();
for(int i=0; i<list.size(); i++){
ProductModel prd = (ProductModel)list.get(i);
System.out.println(String.valueOf(prd.getCardId()));
}
session.getTransaction().commit();
session.close();
return null;
}
}
Connection setup:
package app;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
/**
* Create hibernate configuration.
*/
Configuration c = new Configuration().configure("/resources/hibernate.cfg.xml");
public static SessionFactory createSessionFactory() {
try
{
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.out.print("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
}
Return object model:
package app;
public class ProductModel {
private int retVal;
private int cardId;
public ProductModel(int retVal, int cardId) {
super();
this.retVal = retVal;
this.cardId = cardId;
}
public int getRetVal() {
return retVal;
}
public void setRetVal(int retVal) {
this.retVal = retVal;
}
public int getCardId() {
return cardId;
}
public void setCardId(int cardId) {
this.cardId = cardId;
}
}
Hibernate conf:
<?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="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://.......</property>
<property name="connection.username">user</property>
<property name="connection.password">pass</property>
<property name="connection.pool_size">10</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.connection.autocommit">true</property>
<!--<property name="current_session_context_class">thread</property> -->
<mapping resource="app/PRODUCT_CREATE.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
POM:
<properties>
<java.version>1.8</java.version>
<jdk.version>1.8</jdk.version>
<hibernate.version>4.3.8.Final</hibernate.version>
<hibernate.jpa.version>1.0.0.Final</hibernate.jpa.version>
</properties>
<dependencies>
<!--Hibernate-->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>${hibernate.jpa.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
</dependencies>
Exception:
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.loader.Loader.processResultSet(Loader.java:950)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doList(Loader.java:2554)
at org.hibernate.loader.Loader.doList(Loader.java:2540)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
at org.hibernate.loader.Loader.list(Loader.java:2365)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:353)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1873)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:311)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:141)
at app.App.createProduct(App.java:46)
at app.App.main(App.java:16)
How to fix exception and print out procedure's output parameters in console?

Categories