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
Related
I am new to Spring and while setting all the bean for spring orm configuration, I am getting this error: org.springframework.beans.factory.BeanCreationException
I do not know what exactly I am doing wrong and how to get the desired result.
here is my code:
App.java
package com.spring.orm;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.orm.dao.StudentDao;
import com.spring.orm.entities.Student;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext("config.xml");
StudentDao studentDao= context.getBean("studentDao", StudentDao.class);
Student student=new Student(1, "Ayush Bansal", "Delhi");
studentDao.saveStudent(student);
}
}
studentDao
package com.spring.orm.dao;
import javax.transaction.Transactional;
import org.springframework.orm.hibernate5.HibernateTemplate;
import com.spring.orm.entities.Student;
public class StudentDao {
private HibernateTemplate hibernateTemplate;
#Transactional
public void saveStudent(Student student) {
hibernateTemplate.save(student);
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}
Student.java
package com.spring.orm.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student_details")
public class Student {
#Id
#Column(name="student_id")
private int id;
#Column(name="student_name")
private String name;
#Column(name="student_city")
private String city;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int id, String name, String city) {
super();
this.id = id;
this.name = name;
this.city = city;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<tx:annotation-driven/>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" name="ds">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/myhiber"/>
<property name="username" value="root"/>
<property name="password" value="Vampire#911"/>
</bean>
<bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" name="factory">
<!-- dataSource -->
<property name="dataSource" ref="ds"></property>
<!-- hibernate properties -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<!-- annotated classes -->
<property name="annotatedClasses">
<list>
<value>
com.spring.orm.entities.Student
</value>
</list>
</property>
</bean>
<bean class="org.springframework.orm.hibernate5.HibernateTemplate" name="hibernateTemplate">
<property name="sessionFactory" ref="factory"></property>
</bean>
<bean class="com.spring.orm.dao.StudentDao" name="studentDao">
<property name="hibernateTemplate" ref="hibernateTempLate"></property>
</bean>
<bean class="org.springframework.orm.hibernate5.HibernateTransactionManager" name="transactionManager">
<property name="sessionFactory" ref="factory"/>
</bean>
</beans>
Error
Jul 24, 2021 8:21:58 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.2.Final}
Jul 24, 2021 8:21:58 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Jul 24, 2021 8:21:59 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata : Could not create connection to database server.
Jul 24, 2021 8:21:59 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: drop table if exists student_details
Jul 24, 2021 8:22:00 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 08001
Jul 24, 2021 8:22:00 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Could not create connection to database server.
Jul 24, 2021 8:22:00 PM org.springframework.context.support.AbstractApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'factory' defined in class path resource [config.xml]: Invocation of init method failed; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'factory' defined in class path resource [config.xml]: Invocation of init method failed; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
at com.spring.orm.App.main(App.java:19)
Caused by: org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:48)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:69)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.jdbcStatement(GenerationTargetToDatabase.java:77)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:53)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:375)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:359)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:241)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:154)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:126)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:112)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:145)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:309)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:616)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:600)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792)
... 12 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2588)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2321)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:189)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:154)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:145)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:43)
... 30 more
Caused by: java.lang.NullPointerException: Cannot invoke "java.util.Map.get(Object)" because "this.serverVariables" is null
at com.mysql.jdbc.ConnectionImpl.getServerCharacterEncoding(ConnectionImpl.java:3307)
at com.mysql.jdbc.MysqlIO.sendConnectionAttributes(MysqlIO.java:1985)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1911)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1288)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2506)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2539)
... 50 more
Thanks for helping in advance.
Here is my simple hibernate.cfg.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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/UserDB</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create-drop</property>
<!-- Mapping files -->
<mapping class="com.stackoverflow.model.Person" />
<mapping class="com.stackoverflow.model.Phone" />
</session-factory>
Here is simple Person entity:
#Entity(name = "Person")
public class Person {
#Id
#GeneratedValue
private Long id;
public Person() {
}
}
Here is simple Phone entity:
#Entity(name = "Phone")
public class Phone {
#Id
#GeneratedValue
private Long id;
#Column(name = "`number`")
private String number;
#ManyToOne(cascade=CascadeType.ALL,optional=false)
#JoinColumn(name = "person_id",
foreignKey = #ForeignKey(name = "PERSON_ID_FK")
)
private Person person;
public Phone() {
}
public Phone(String number) {
this.number = number;
}
public Long getId() {
return id;
}
public String getNumber() {
return number;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
Here is junit test class that tries to save this relationship into database:
public class TestManyToOne {
private static SessionFactory sessionFactory;
private Session session;
#BeforeClass
public static void setUp() throws Exception {
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
.build();
try {
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had
// trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy(registry);
System.out.println("Exception\n" + e);
}
assertNotNull(sessionFactory);
}
#AfterClass
public static void tearDown() throws Exception {
sessionFactory.close();
}
#Before
public void beforeEach() {
session = sessionFactory.getCurrentSession();
session.beginTransaction();
}
#After
public void afterEach() {
session.getTransaction().commit();
session.close();
}
#Test
public void testSave() {
Person person = new Person();
Phone phone1 = new Phone("93283287832");
Phone phone2 = new Phone("0987654321");
phone1.setPerson(person);
phone2.setPerson(person);
session.save(phone1);
session.save(phone2);
}
}
It has only one #Test method called testSave. When I run it on just created database I get error :
Hibernate:
alter table Phone
drop
foreign key PERSON_ID_FK
апр 11, 2017 5:50:54 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#6f2cfcc2] 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.
апр 11, 2017 5:50:54 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:62)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:374)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:359)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applyConstraintDropping(SchemaDropperImpl.java:331)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:230)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:154)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:126)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:112)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:137)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:307)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:490)
at org.hibernate.boot.internal.MetadataImpl.buildSessionFactory(MetadataImpl.java:170)
at com.stackoverflow.dao.TestDao.setUp(TestDao.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
Hibernate:
drop table if exists hibernate_sequence
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'userdb.phone' 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:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:734)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:49)
... 30 more
In error this line is important:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'userdb.phone' doesn't exist
How to tell hibernate do not drop foreign key constraint before creating tables?
Thank you.
I didn't believe it but the problem was that connection pool size was set to 1. After I set it to ten
<property name="connection.pool_size">10</property>
junit test runs succesfully but the error didn't disappear. It is ignored by eclipse.
I am learning hibernate for the first time so unable to find the error.
The student007 table is created in the database then i executed the client class. By analyzing the error what i understand is there is a problem with the sessionfactory part. also there is an error with the oracle driver saying class not found exception
student.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.Student" table="student007" schema="system">
<id name="id" column="sid"/>
<property name="name" column="sname"/>
<property name="email" column="semail"/>
<property name="marks" column="smarks"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.oracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">manager</property>
<property name="connection.pool_size">10</property>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<mapping resource="resource/student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
client.java
package test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import beans.Student;
public class Client {
public static void main(String[] args) {
Student st = new Student();
st.setId(111);
st.setName("Ishan");
st.setEmail("abx#gmail.com");
st.setMarks(90);
Configuration cfg = new Configuration();
cfg.configure("resource/hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
//The error appears to be in the above line while building the session factory.
Session s = sf.openSession();
s.save(st);
s.beginTransaction().commit();
s.evict(st);
}
}
student.java
package beans;
public class Student {
private int id;
private String name;
private String email;
private int marks;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
public Student() {
// TODO Auto-generated constructor stub
}
}
I am getting this error please help
Jan 16, 2017 7:10:09 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.6.Final}
Jan 16, 2017 7:10:09 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 16, 2017 7:10:10 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jan 16, 2017 7:10:10 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:267)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at test.Client.main(Client.java:21)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [oracle.jdbc.oracleDriver]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:348)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.loadDriverIfPossible(DriverManagerConnectionProviderImpl.java:160)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator(DriverManagerConnectionProviderImpl.java:116)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:100)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:72)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:257)
... 14 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : oracle.jdbc.oracleDriver
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:336)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:345)
... 26 more
The exception message says it all: Could not load requested class : oracle.jdbc.oracleDriver
So the first thing I check if you misspelled the name of the driver and you really do. The class names starts with upper-case letters.
The correct name of the driver should be: oracle.jdbc.OracleDriver.
I am getting the following error while trying to connect to mysql using hibernate. I have a Super class Employee and three subclasses: SoftwareEmployee, HardWareEmployee and Admin.I also have two xml files: hibernateisapersubclass.cfg.xml and employeeisapersubclass.hbm.xml. I am trying to populate data in 4 different table using 'joined-subclass' tag in my xml. Please help.
Error that I am getting are as follows:
Dec 04, 2016 7:45:34 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.5.Final}
Dec 04, 2016 7:45:34 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Dec 04, 2016 7:45:34 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/hqlstudent]
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Sun Dec 04 19:45:35 EST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Dec 04, 2016 7:45:35 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Dec 04, 2016 7:45:36 PM org.hibernate.AssertionFailure <init>
ERROR: HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: Table hqlstudent.superemployee not found
Dec 04, 2016 7:45:36 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost/hqlstudent]
Exception in thread "main" org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.JoinedSubclassEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:112)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:128)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:297)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:445)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at test.ClientIsAPerSubClass.main(ClientIsAPerSubClass.java:22)
Caused by: org.hibernate.AssertionFailure: Table hqlstudent.superemployee not found
at org.hibernate.persister.entity.AbstractEntityPersister.getTableId(AbstractEntityPersister.java:5168)
at org.hibernate.persister.entity.JoinedSubclassEntityPersister.<init>(JoinedSubclassEntityPersister.java:433)
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 org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
... 7 more
Following are my five java files and two xml files:
ClientIsAPerSubClass.java
package test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import beans.Admin;
import beans.Admin1;
import beans.HardwareEmployee;
import beans.HardwareEmployee1;
import beans.SoftwareEmployee;
import beans.SoftwareEmployee1;
public class ClientIsAPerSubClass {
public static void main(String [] args){
Configuration configuration = new Configuration();
configuration.configure("resources/hibernateisapersubclass.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction= session.beginTransaction();//student object will move database;
SoftwareEmployee1 softwareEmployee= new SoftwareEmployee1();
softwareEmployee.setId(1);
softwareEmployee.setName("bishwash");
softwareEmployee.setEmail("20wash.sharma#gmail.com");
softwareEmployee.setSalary(60000);
softwareEmployee.setTool("hibernate");
HardwareEmployee1 hardwareEmployee = new HardwareEmployee1();
hardwareEmployee.setId(2);
hardwareEmployee.setName("mahendra");
hardwareEmployee.setEmail("mahendra#mahendra.com");
hardwareEmployee.setSalary(55000);
hardwareEmployee.setWorkinghour(20);
Admin1 admin= new Admin1();
admin.setId(3);
admin.setName("ashish#ashish.com");
admin.setEmail("mahendra#mahendra.com");
admin.setSalary(60000);
admin.setBranchname("Kathmandu");;
session.save(softwareEmployee);
session.save(hardwareEmployee);
session.save(admin);
transaction.commit();
session.close();
sessionFactory.close();
//System.out.println("no of rows dumped from old to new table"+i);
}
}
Admin.java
package beans;
public class Admin extends Employee {
private String branchname;
public Admin() {
}
public Admin(int id, String name, String email, double salary, String branchname) {
super(id, name, email, salary);
this.branchname= branchname;
}
public String getBranchname() {
return branchname;
}
public void setBranchname(String branchname) {
this.branchname = branchname;
}
}
package beans;
public class HardwareEmployee extends Employee {
private int workinghour;
public HardwareEmployee() {
super();
// TODO Auto-generated constructor stub
}
public HardwareEmployee(int id, String name, String email, double salary, int workinghour) {
super(id, name, email, salary);
this.workinghour= workinghour;
}
public int getWorkinghour() {
return workinghour;
}
public void setWorkinghour(int workinghour) {
this.workinghour = workinghour;
}
}
SoftwareEmployee.java
package beans;
public class SoftwareEmployee extends Employee {
private String tool;
public SoftwareEmployee() {
super();
// TODO Auto-generated constructor stub
}
public SoftwareEmployee(int id, String name, String email, double salary ,String tool) {
super(id, name, email, salary);
this.tool= tool;
}
public String getTool() {
return tool;
}
public void setTool(String tool) {
this.tool = tool;
}
}
HardwareEmployee.java
package beans;
public class HardwareEmployee extends Employee {
private int workinghour;
public HardwareEmployee() {
super();
// TODO Auto-generated constructor stub
}
public HardwareEmployee(int id, String name, String email, double salary, int workinghour) {
super(id, name, email, salary);
this.workinghour= workinghour;
}
public int getWorkinghour() {
return workinghour;
}
public void setWorkinghour(int workinghour) {
this.workinghour = workinghour;
}
}
employeeisapersubclass.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.Employee" table ="superemployee" schema="hqlstudent">
<id name="id"/>
<property name="name" />
<property name="email" />
<property name="salary" />
<joined-subclass name="beans.SoftwareEmployee" table="softwareemployee">
<key column ="id"/>
<property name="tool"/>
</joined-subclass>
<joined-subclass name="beans.HardwareEmployee" table="hardwareemployee">
<key column ="id"/>
<property name="workinghour"/>
</joined-subclass>
<joined-subclass name="beans.Admin" table="admin">
<key column ="id"/>
<property name="branchname"/>
</joined-subclass>
</class>
</hibernate-mapping>
hibernateisapersubclass.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.hbm2ddl.auto">
create
</property>
<property name="hibernate.show_sql">
true
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume customstudent is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/hqlstudent
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
password
</property>
<mapping resource="resources/employeeisapersubclass.hbm.xml"/>
</session-factory>
</hibernate-configuration>
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)");