WARN: SQL Error: 1064, SQLState: 42000 - java

I have a problem with hibernate query.
UPDATE:
When I use this query it works like a charm:
public static List<Korisnik> UzmiSveKorisnike()
{
EntityManager em = Konekcija.getEmf().createEntityManager();
TypedQuery<Korisnik> q = em.createQuery("select k from Korisnik k where k.isActive = 1", Korisnik.class);
List<Korisnik> resultList = q.getResultList();
em.close();
return resultList;
}
But when I use one listed below, to select single result (like for login)...
I get this error: WARN: SQL Error: 1064, SQLState: 42000
I have tried variety of ways to implement this query, but without success. I will list them at the end of the post.
This is the code:
public static Korisnik ProvjeraKorisnickihPodataka(String kIme, String kLozinka)
{
EntityManager em = Konekcija.getEmf().createEntityManager();
{
TypedQuery<Korisnik> q = em.createQuery("select k from Korisnik k where k.isActive = 1 AND k.korisnickoIme=:ime AND k.lozinka =:lozinka", Korisnik.class);
q.setParameter("ime", kIme);
q.setParameter("lozinka", kLozinka);
Korisnik provjeren = q.getSingleResult();
em.close();
return provjeren;
Even if I replace :ime and :lozinka with actual data like "k.korisnickoIme='msbtest' and k.lozinka = 'msbtest'" I get the same error.
Your help is appreciated.
Thank you!
Complete stack:
Hibernate: select TOP(?) korisnik0_.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, korisnik0_.ime as ime11_, korisnik0_.isActive as isActive11_, korisnik0_.kontakt as kontakt11_, korisnik0_.korisnickoIme as korisnic5_11_, korisnik0_.lozinka as lozinka11_, korisnik0_.prezime as prezime11_, korisnik0_.rola_RolaID as rola9_11_ from Korisnik korisnik0_ where korisnik0_.isActive=1 and korisnik0_.korisnickoIme=? and korisnik0_.lozinka=?
Jul 05, 2013 11:45:22 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1064, SQLState: 42000
Jul 05, 2013 11:45:22 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: 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 '.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, k' at line 1
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: 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 '.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, k' at line 1
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1377)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:318)
at Servis.LoginServis.ProvjeraKorisnickihPodataka(LoginServis.java:35)
at UI.LogInFrm.do_btnPrijava_widgetSelected(LogInFrm.java:173)
at UI.LogInFrm$1.widgetSelected(LogInFrm.java:121)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at UI.LogInFrm.main(LogInFrm.java:44)
Caused by: org.hibernate.exception.SQLGrammarException: 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 '.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, k' at line 1
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy10.executeQuery(Unknown Source)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1926)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1727)
at org.hibernate.loader.Loader.doQuery(Loader.java:852)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:293)
at org.hibernate.loader.Loader.doList(Loader.java:2411)
at org.hibernate.loader.Loader.doList(Loader.java:2397)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2227)
at org.hibernate.loader.Loader.list(Loader.java:2222)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1247)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:285)
... 9 more
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 '.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, k' at line 1
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:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2322)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 25 more
mapping goes like this:
/**
** Class Korisnik
**/
#Entity
public class Korisnik implements Serializable {
//Fields
#Id
#GeneratedValue
private Integer KorisnikID;
private String ime;
private String prezime;
private String kontakt;
private String korisnickoIme;
private String lozinka;
private Boolean isActive;
#JoinColumn(nullable = false)
#ManyToOne
private Agencija agencija;
#JoinColumn(nullable = false)
#ManyToOne
private Rola rola;
and getters and setters go...
OK, my persistence.xml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="MojaOznaka1" transaction-type="RESOURCE_LOCAL">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<!-- Podaci o bazi podataka -->
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://xxxxxxxxx.xxxxxxxxx.xxx/xxxxxxxxx/" />
<property name="javax.persistence.jdbc.user" value="xxxxxx" />
<property name="javax.persistence.jdbc.password" value="xxxxxx" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<!-- hiberante dialect -->
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServer2008Dialect" />
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size" value="1" />
<!-- Ispis SQL koda u konzolu -->
<property name="hibernate.show_sql" value="true" />
<!-- formatiranje SQL koda ispisanog u konzolni prozor -->
<property name="hibernate.format_sql" value="false" />
<!-- Vrijednost "update" kreira tabele ako nepostoje -->
<!-- <property name="hibernate.hbm2ddl.auto" value="update" /> -->
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class" value="thread" />
<!-- Disable the second-level cache -->
<property name="cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
<!-- automatsko prepoznavanje JPA klasa -->
<property name="hibernate.archive.autodetection" value="class, hbm" />
</properties>
</persistence-unit>
</persistence>
OK, now what???

The query output you give suggests you told Hibernate to generate SQL for a MS-SQL Server (using TOP(1) to fetch the topmost row).
Since you're using a mysql database as a backend, that won't work. Try adding
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
to your persistence.xml or wherever you configure JPA.
As #Secko mentions in the comment, omitting the dialect altogether might even select a better (more specific) one.

This error usually indicates some mapping error. Are all fields used in the where are actually fields of the "Korisnik" class? HQL uses the field names and not the column names from the database.

Related

java.sql.SQLException: Connection is closed using HikariCP [ JPA + Hibernate + Guice]

I am frequently getting this exception :
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1423)
at org.hibernate.query.Query.getResultList(Query.java:146)
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:72)
at com.inmobi.programmatics.myservice.dao.impl.AbstractDAOImpl.getByIds(AbstractDAOImpl.java:117)
Caused by: org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1940)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1909)
Caused by: java.sql.SQLException: Connection is closed
at com.zaxxer.hikari.pool.ProxyConnection$ClosedConnection$1.invoke(ProxyConnection.java:469)
at com.sun.proxy.$Proxy66.prepareStatement(Unknown Source)
at com.zaxxer.hikari.pool.ProxyConnection.prepareStatement(ProxyConnection.java:310)
at com.zaxxer.hikari.pool.HikariProxyConnection.prepareStatement(HikariProxyConnection.java)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
Here is my configuration for using HikariCP with JPA Hibernate :
JpaPersistModule jpaPersistModule = new JpaPersistModule("persistenceConfig");
final Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.hikari.dataSource.url",
"jdbc:postgresql://" + configurationData.getDBHost() + ":" + configurationData.getDBPort()
+ "/" + configurationData.getDBName() + "?stringtype=unspecified");
properties.put("hibernate.hikari.dataSource.user", configurationData.getDBUser());
properties.put("hibernate.hikari.dataSource.password", configurationData.getDBPassword());
properties.put("hibernate.hikari.minimumIdle", "2");
properties.put("hibernate.hikari.maximumPoolSize", "8");
properties.put("hibernate.hikari.connectionTimeout", "30000");
properties.put("hibernate.hikari.idleTimeout", "60000");
properties.put("hibernate.hikari.poolName", "master_pool");
properties.put("hibernate.hikari.leakDetectionThreshold", "60000");
properties.put("hibernate.hikari.maxLifetime", "600000");
properties.put("hibernate.hikari.connectionTestQuery", "select 1");
properties.put("hibernate.hikari.connectionInitSql", "select 1");
Here is my peristence.xml for JPA:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="persistenceConfig" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL94Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.jdbc.time_zone" value="UTC"/>
<property name="hibernate.jdbc.batch_size" value="25"/>
<property name="hibernate.connection.provider_class" value="org.hibernate.hikaricp.internal.HikariCPConnectionProvider"/>
<property name="hibernate.hikari.dataSourceClassName" value="org.postgresql.ds.PGSimpleDataSource"/>
</properties>
</persistence-unit>
</persistence>
I have checked idle_in_transaction_session_timeout in postgres db is 1 hour. It means there is no issue from db side.
I have tried to adjust hikaricp configuration. But it is not helping.
Initially I thought it maybe because of leak connection for which I added leakDetectionThreshold to 60 sec.
Then again I thought it maybe because of getting invalid connection from pool for which I have set connectionTestQuery. But it's also not helping.
I have checked there is maximum 1 or 2 connection are active at any time. So it can't be maxpool size issue.
I have looked into this stackoverflow question. It is not making any sense for my problem statement as I am using entitymanager with Guice Transactional.So I don't need to care about connection closing which will take care by Guice Transactional.
Can anyone help with it ?

java.sql.SQLException: invalid arguments in call

I am learning to integrate hibernate with spring to connect to Oracle 11g using the below code. But stuck with the same error from few days. Please help me resolve this. i have tried the different solutions mentioned in other answers given for questions with the same error, but no luck.
Any relevant solutions welcome.
Thanks,
Nisha
spring.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="serverDatasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" >
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url" >
<value>jdbc:oracle:thin:#10.23.225.22:1521:PRACTICE</value>
</property>
<!-- <property name="username" value="SCOTT"/>
<property name="password" value="tiger"/>-->
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter">
<property name="targetDataSource" ref="serverDatasource"/>
<property name="username"><value>SCOTT</value></property>
<property name="password"><value>tiger</value></property>
</bean>
<!-- Hibernate 5 SessionFactory bean definition -->
<bean id="Hibernate5SessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.springHibernate.model.Person</value>
</list>
</property>
<property name="HibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="personDao" class="com.springHibernate.dao.PersonDaoImpl">
<property name="sessionFactory" ref="Hibernate5SessionFactory"></property>
</bean>
</beans>
Main Method: SpringHibernateMain
package com.springHibernate.main;
import java.util.List;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.springHibernate.dao.PersonDao;
import com.springHibernate.model.Person;
public class SpringHibernateMain {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
PersonDao personDao = context.getBean(PersonDao.class);
Person p = new Person();
p.setId(1);
p.setName("John");
p.setCountry("United States");
personDao.save(p);
List<Person> person = personDao.listPerson();
for(Person p1 : person){
System.out.println("Person List:" + p1);
}
}
}
Stack Trace:
ERROR: Unable obtain JDBC Connection
java.sql.SQLException: invalid arguments in call
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:236)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:414)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:130)
at org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter.doGetConnection(UserCredentialsDataSourceAdapter.java:162)
at org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter.getConnection(UserCredentialsDataSourceAdapter.java:145)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.internal.SessionFactoryImpl$3.obtainConnection(SessionFactoryImpl.java:643)
at org.hibernate.hql.spi.id.IdTableHelper.executeIdTableCreationStatements(IdTableHelper.java:67)
at org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:125)
at org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:42)
at org.hibernate.hql.spi.id.AbstractMultiTableBulkIdStrategyImpl.prepare(AbstractMultiTableBulkIdStrategyImpl.java:88)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:451)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
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:416)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:401)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.springHibernate.main.SpringHibernateMain.main(SpringHibernateMain.java:14)
May 16, 2016 12:59:16 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 17433, SQLState: null
May 16, 2016 12:59:16 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: invalid arguments in call
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
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.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:87)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:109)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:227)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:234)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:214)
at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:52)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1525)
at com.springHibernate.dao.PersonDaoImpl.save(PersonDaoImpl.java:25)
at com.springHibernate.main.SpringHibernateMain.main(SpringHibernateMain.java:24)
Caused by: java.sql.SQLException: invalid arguments in call
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:236)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:414)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:130)
at org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter.doGetConnection(UserCredentialsDataSourceAdapter.java:162)
at org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter.getConnection(UserCredentialsDataSourceAdapter.java:145)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:386)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:84)
... 8 more
As It is mentioned in the Stacktrace it is unable to get the connection.
invalid arguments in call
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
In datasource driver name should be like below
<value>oracle.jdbc.OracleDriver</value>
In procedure if we give incorrect type mapping from java type to oracle data type then we will get
org.springframework.jdbc.UncategorizedSQLException: CallableStatementCallback; uncategorized SQLException for proc SQL state [99999]; error code [17068]; Invalid argument(s) in call; nested exception is java.sql.SQLException: Invalid argument(s) in call
To fix this we need to map respective data type.
Instead
PersonDao personDao = context.getBean(PersonDao.class);
Try with
PersonDao personDao = (PersonDao) context.getBean("personDao");
So your Bean Id in spring.xml
Solved this, at last, by adding just the jars in lib/required folder of Hibernate zip file. Till then i had added all the jars in the lib folder.

Mapping an java object to a database

I am tring to map a java object to database(i am using postgres). when i am runnig the java file (HibernateTest.java) it is showing lot of errors. i think all thing are correct. but i am doubtfull in my eclipse,bcoz it is not supporting xml ( i mean it is not showing color, it is not taking xml file as a know file ). i am a beginner so i cant understand them. plz suggest me.
hibernate.cfg.xml file
<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration
xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-configuration hibernate-configuration-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost:5432/hibernatedb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">hkm#1160</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQlDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping resource="org.hibernate.hemant.dto.UDestails"/>
</session-factory>
</hibernate-configuration>
UserDetails.java file
package org.hibernate.hemant.dto;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class UserDetails
{
#Id
private int userID;
private String userName;
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
my main java file HibernateTest.java
package org.hemant.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.hemant.dto.UserDetails;
public class HibernateTest {
/**
* #param args
*/
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserID(1);
user.setUserName("First user");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.beginTransaction().commit();
}
}
There are the errors......
Apr 13, 2016 9:26:08 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
Apr 13, 2016 9:26:08 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Apr 13, 2016 9:26:08 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassistException in thread "main"
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 13 and column 63 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 org.hibernate.cfg.Configuration.configure(Configuration.java:245)
at org.hemant.hibernate.HibernateTest.main(HibernateTest.java:15)
Caused by: javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 13; columnNumber: 63; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(Unknown Source)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:126)
... 6 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 13; columnNumber: 63; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.handleStartElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(Unknown Source)
... 9 more
The cause of exception is an incorrect hibernate.cfg.xml file.
Please, use this structure
<!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>
...
<mapping class="org.hibernate.hemant.dto.UDestails" />
</session-factory>
</hibernate-configuration>
You incorrect specify a persistent class in hibernate.cfg.xml. You use a mapping with annotations so you need to map a class not a resource
<mapping class="org.hibernate.hemant.dto.UDestails" />
Please, don't forget to close a session and sessionFactory.

hibernate 5 configuration for oracle11g in eclipse

I am trying to configure hibernate 5 to access oracle 11 g in eclipse.
hibernate.cfg.xml is as follows:
In following xml i have specified database credentials(url, username and password),dilect, mapping class, show_sql . I want to ask if I missed any important property.
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<!-- <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#127.0.0.1:1521:orcl</property> -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#127.0.0.1:1521:XE</property>
<property name="connection.username">SYSTEM</property>
<property name="connection.password">motog</property>
<mapping class="com.demo.one.Hello"/>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.OracleDialect
</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>
<!-- Echo all executed SQL to stdout -->
<property name="hibernate.show_sql">true</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"/>
</session-factory>
</hibernate-configuration>
[image specifies project structure and imported libraries][1]
Defined Hello class as Table name by using #Entity and userId as primary key by using #Id
Hello.java:
package com.demo.one;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Hello {
#Id
private int userId;
private String userName;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
} // end of Hello.java
Following class tries to save instance of Hello in database.
OracleTest.java:
package com.demo.one;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class OracleTest {
public static void main(String[] args) {
Hello z = new Hello();
z.setUserId(2);
z.setUserName("ashish");
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(z);
session.getTransaction().commit();
}
} // End of OracleTest.java
I am trying to save Hello class's object in oracle 11g XE database(resides on my local machine) , OracleTest.java is written for that.
I am getting following errors.
Jan 17, 2016 6:08:01 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.7.Final}
Jan 17, 2016 6:08:01 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 17, 2016 6:08:01 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number -1 and column -1 in RESOURCE hibernate.cfg.xml. Message: cvc-complex-type.2.4.a: Invalid content was found starting with element 'property'. One of '{"http://www.hibernate.org/xsd/orm/cfg":mapping, "http://www.hibernate.org/xsd/orm/cfg":class-cache, "http://www.hibernate.org/xsd/orm/cfg":collection-cache, "http://www.hibernate.org/xsd/orm/cfg":event, "http://www.hibernate.org/xsd/orm/cfg":listener}' is expected.
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 org.hibernate.cfg.Configuration.configure(Configuration.java:245)
at com.demo.one.OracleTest.main(OracleTest.java:13)
Caused by: javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; cvc-complex-type.2.4.a: Invalid content was found starting with element 'property'. One of '{"http://www.hibernate.org/xsd/orm/cfg":mapping, "http://www.hibernate.org/xsd/orm/cfg":class-cache, "http://www.hibernate.org/xsd/orm/cfg":collection-cache, "http://www.hibernate.org/xsd/orm/cfg":event, "http://www.hibernate.org/xsd/orm/cfg":listener}' is expected.]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(Unknown Source)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:126)
... 6 more
Caused by: org.xml.sax.SAXParseException; cvc-complex-type.2.4.a: Invalid content was found starting with element 'property'. One of '{"http://www.hibernate.org/xsd/orm/cfg":mapping, "http://www.hibernate.org/xsd/orm/cfg":class-cache, "http://www.hibernate.org/xsd/orm/cfg":collection-cache, "http://www.hibernate.org/xsd/orm/cfg":event, "http://www.hibernate.org/xsd/orm/cfg":listener}' is expected.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.handleStartElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(Unknown Source)
... 9 more
please guide me, its my first encounter with hibernate.
PS: please check attached image. link is at the bottom.
regards
ashish
[1]: http://i.stack.imgur.com/DBYxu.png
The error message tells you that it's not expecting a <property> element somewhere. Instead, it expects a <mapping> element, or a <class-cache> element, or...
And indeed, the DTD has the following definition:
<!ELEMENT session-factory (property*, mapping*, (class-cache|collection-cache)*, event*, listener*)>
This means that, under <session-factory>, you're supposed to have 0 or more <property> elements, then 0 or more <mapping> elements.
But your xml file has
<property name="connection.password">motog</property>
<mapping class="com.demo.one.Hello"/>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
So you have a <mapping>element in the middle of <property> elements. That is thus invalid.

How does hibernate resolve schema for initially validating to a Teradata database?

Environment:
Java/Spring application that uses JPA/Hibernate for persistence and connects to a Teradata datasource configured in the app container (Tomcat) which is accessed through JNDI.
Versions that I am using:
java: 6
spring: 3.2.4.RELEASE
hibernate.core: 4.2.4.Final
hibernate.entitymanager: 4.2.4.Final
hibernate.validator: 5.0.1.Final
springdata: 1.3.4.RELEASE
javax.validation: 1.1.0.Final
Problem:
There are two Teradata databases in the same server that have a same named table but with different columns:
DatDe001.SFITEM
Columns: [iipcst, iidesc, iivend, updated_at, iisku#, created_at, item_expdt, item_effdt]
DEV_DIG_UMT.SFITEM
Columns: [iipcst, iidesc, iivend, row_updt_tms, iisku#, row_insrt_tms, item_expdt, item_effdt]
As you can see the columns that differ are updated_at -> row_updt_tms and created_at -> row_insrt_tms
I am using a JNDI datasource which is configured using this jdbc url:
jdbc:teradata://<server_ip>/DATABASE=DEV_DIG_UMT,DBS_PORT=1025,COP=OFF,CHARSET=UTF8,TMODE=ANSI
It is supposed that the jdbc connection will resolve the location of the table using the DATABASE value in that jdbc url. However Hibernate seems to be taking the wrong one: DatDe001.SFITEM when performing the initial schema validation, that is at the moment of context initialization when Spring tries to create the EntityManagerFactory bean:
2013-08-15 13:32:03,635 INFO localhost-startStop-1 org.hibernate.tool.hbm2ddl.TableMetadata - HHH000261: Table found: DatDe001.SFITEM
2013-08-15 13:32:03,635 INFO localhost-startStop-1 org.hibernate.tool.hbm2ddl.TableMetadata - HHH000037: Columns: [iipcst, iidesc, iivend, updated_at, iisku#, created_at, item_expdt, item_effdt]
So as my JPA entity (see the entity below in the post) does not have those columns, the hibernate validation throws an exception (see the summarized stack trace):
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [C:\APP\springsource\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\profile-items\WEB-INF\classes\META-INF\spring\applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: persistenceUnit] Unable to build EntityManagerFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in file [C:\APP\springsource\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\profile-items\WEB-INF\classes\META-INF\spring\applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: persistenceUnit] Unable to build EntityManagerFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
...
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: persistenceUnit] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:924)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
...
Caused by: org.hibernate.HibernateException: Missing column: row_updt_tms in DatDe001.SFITEM
at org.hibernate.mapping.Table.validateColumns(Table.java:366)
at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1305)
at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:155)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:508)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1790)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
After I saw that, I was wondering if this behavior will persist when executing a query statement to the db through JPA/hibernate, or if it will point to the right table in that case.
Then just for investigation purposes I changed my JPA entity to have the same columns that DatDe001.SFITEM table:
#Entity
public class Sfitem implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private SfitemPK id;
#Column(name="\"iidesc\"")
private String iidesc;
#Column(name="\"iipcst\"")
private BigDecimal iipcst;
#Column(name="\"iivend\"")
private BigDecimal iivend;
#Temporal
#Column(name="\"item_expdt\"")
private Date itemExpdt;
#Temporal
#Column(name="\"created_at\"")
private Date createdAt;
#Temporal
#Column(name="\"updated_at\"")
private Date updatedAt;
...
}
I started the application and it got loaded successfully. Instead of showing the exception now the log looked good:
...
2013-08-15 14:42:52,056 INFO localhost-startStop-1 org.hibernate.tool.hbm2ddl.TableMetadata - HHH000261: Table found: DatDe001.SFITEM
2013-08-15 14:42:52,056 INFO localhost-startStop-1 org.hibernate.tool.hbm2ddl.TableMetadata - HHH000037: Columns: [iipcst, iidesc, iivend, updated_at, iisku#, created_at, item_expdt, item_effdt]
2013-08-15 14:42:52,061 DEBUG localhost-startStop-1 org.hibernate.internal.SessionFactoryImpl - Checking 0 named HQL queries
2013-08-15 14:42:52,061 DEBUG localhost-startStop-1 org.hibernate.internal.SessionFactoryImpl - Checking 0 named SQL queries
2013-08-15 14:42:52,063 TRACE localhost-startStop-1 org.hibernate.service.internal.AbstractServiceRegistryImpl - Initializing service [role=org.hibernate.service.config.spi.ConfigurationService]
2013-08-15 14:42:52,113 TRACE localhost-startStop-1 org.hibernate.service.internal.AbstractServiceRegistryImpl - Initializing service [role=org.hibernate.stat.spi.StatisticsImplementor]
...
I tried to execute a query to the table and surprisingly found that this time Hibernate was pointing to the right database/schema: DEV_DIG_UMT, the query failed because now the entity had the columns for the other database: DatDe001, see the log:
2013-08-15 14:50:05,731 TRACE tomcat-http--4 org.hibernate.engine.query.spi.QueryPlanCache - Located HQL query plan in cache (SELECT o FROM Sfitem o WHERE o.id.iisku = :iisku AND o.id.itemEffdt <= :date AND coalesce(o.itemExpdt, cast('9999-12-31' as date)) >= :date)
2013-08-15 14:50:05,766 TRACE tomcat-http--4 org.hibernate.engine.query.spi.QueryPlanCache - Located HQL query plan in cache (SELECT o FROM Sfitem o WHERE o.id.iisku = :iisku AND o.id.itemEffdt <= :date AND coalesce(o.itemExpdt, cast('9999-12-31' as date)) >= :date)
2013-08-15 14:50:05,768 TRACE tomcat-http--4 org.hibernate.engine.query.spi.HQLQueryPlan - Find: SELECT o FROM Sfitem o WHERE o.id.iisku = :iisku AND o.id.itemEffdt <= :date AND coalesce(o.itemExpdt, cast('9999-12-31' as date)) >= :date
2013-08-15 14:50:05,772 TRACE tomcat-http--4 org.hibernate.engine.spi.QueryParameters - Named parameters: {iisku=387671, date=2013-08-08}
2013-08-15 14:50:05,810 DEBUG tomcat-http--4 org.hibernate.SQL - select sfitem0_."iisku#" as iisku1_0_, sfitem0_."item_effdt" as item_eff2_0_, sfitem0_."created_at" as created_3_0_, sfitem0_."iidesc" as iidesc4_0_, sfitem0_."iipcst" as iipcst5_0_, sfitem0_."iivend" as iivend6_0_, sfitem0_."item_expdt" as item_exp7_0_ from sfitem sfitem0_ where sfitem0_."iisku#"=? and sfitem0_."item_effdt"<=? and coalesce(sfitem0_."item_expdt", cast('9999-12-31' as DATE))>=?
2013-08-15 14:50:05,832 DEBUG tomcat-http--4 org.hibernate.engine.jdbc.spi.SqlExceptionHelper - could not prepare statement [select sfitem0_."iisku#" as iisku1_0_, sfitem0_."item_effdt" as item_eff2_0_, sfitem0_."created_at" as created_3_0_, sfitem0_."iidesc" as iidesc4_0_, sfitem0_."iipcst" as iipcst5_0_, sfitem0_."iivend" as iivend6_0_, sfitem0_."item_expdt" as item_exp7_0_ from sfitem sfitem0_ where sfitem0_."iisku#"=? and sfitem0_."item_effdt"<=? and coalesce(sfitem0_."item_expdt", cast('9999-12-31' as DATE))>=?]
com.teradata.jdbc.jdbc_4.util.JDBCException: [Teradata Database] [TeraJDBC 14.00.00.21] [Error 3810] [SQLState 42S22] Column/Parameter 'DEV_DIG_UMT.sfitem0_.created_at' does not exist.
at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDatabaseSQLException(ErrorFactory.java:307)
at com.teradata.jdbc.jdbc_4.statemachine.ReceiveInitSubState.action(ReceiveInitSubState.java:102)
at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.subStateMachine(StatementReceiveState.java:320)
at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.action(StatementReceiveState.java:201)
at com.teradata.jdbc.jdbc_4.statemachine.StatementController.runBody(StatementController.java:121)
at com.teradata.jdbc.jdbc_4.statemachine.StatementController.run(StatementController.java:112)
...
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:161)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:159)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1859)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1836)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1816)
at org.hibernate.loader.Loader.doQuery(Loader.java:900)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
at org.hibernate.loader.Loader.doList(Loader.java:2526)
at org.hibernate.loader.Loader.doList(Loader.java:2512)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
at org.hibernate.loader.Loader.list(Loader.java:2337)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
This means that hibernate validation and the query executor routines are behaving differently
The entity with the correct fields:
#Entity
public class Sfitem implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private SfitemPK id;
#Column(name="\"iidesc\"")
private String iidesc;
#Column(name="\"iipcst\"")
private BigDecimal iipcst;
#Column(name="\"iivend\"")
private BigDecimal iivend;
#Column(name="\"item_expdt\"")
private Date itemExpdt;
#Column(name="\"row_insrt_tms\"")
private Timestamp rowInsrtTms;
#Column(name="\"row_updt_tms\"")
private Timestamp rowUpdtTms;
...
}
Persistence.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.TeradataDialect"/>
<!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
<!-- Uncomment the following two properties for JBoss only -->
<!-- property name="hibernate.validator.apply_to_ddl" value="false" /-->
<!-- property name="hibernate.validator.autoregister_listeners" value="false" /-->
</properties>
</persistence-unit>
</persistence>
Datasource and entity manager beans:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="${datasource.jndiName}"/>
<property name="lookupOnStartup" value="true"/>
<property name="resourceRef" value="true" />
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
</bean>
Is that a bug or a configuration issue? Has anyone faced this same issue?
I don't want to configure a default schema in the persistence unit nor in the entities, because the approach we are following is to keep the datasource configuration outside the application and in a single place by using the JNDI datasource defined in the container context. That way we don't need to worry when deploying to different environments (Dev, QA, Prod, etc)
You may need to fully qualify your table name in your SELECT queries that are being submitted to Teradata.
select sfitem0_."iisku#" as iisku1_0_, sfitem0_."item_effdt" as item_eff2_0_,
sfitem0_."created_at" as created_3_0_, sfitem0_."iidesc" as iidesc4_0_,
sfitem0_."iipcst" as iipcst5_0_, sfitem0_."iivend" as iivend6_0_,
sfitem0_."item_expdt" as item_exp7_0_
from DatDe001.SFITEM sfitem0_ /* Notice database name is included here */
where sfitem0_."iisku#"=?
and sfitem0_."item_effdt"<=?
and coalesce(sfitem0_."item_expdt", cast('9999-12-31' as DATE))>=?
Edit
You could also construct a string that you execute before each SELECT statement that specifies the schema/database you wish to use as the default database to be used to find objects that are not fully qualified in your SQL:
DATABASE=?
Then possibly use a parameter to provide that value like you are the values for your WHERE clause
Edit 2
You can only specify a single DATABASE parameter for a given connection string. If your requirement is to allow for different names for the database supporting the application front end you will need to parameterize the connection string for each database that the application will need to communicate with on the backend.

Categories