No database connection after deployment (Java Hibernate) - java

I am creating an app for school that generates business rules.
The front end consists of Apex and the backend is a java application that uses hibernate to access the database.
To communicate between Apex and Java I am using a rest service (using struts2).
This works fine when I deploy the application in my IDE (netbeans). But then it runs on my localhost. This way the Apex application can not connect to it. (The Apex application is hosted by my school)
So I tried deploying my application using various websites. The rest service part still works and I can connect the java app with my Apex application.
The problem is that the java application cant seem to connect to the database as soon as i deploy it online.
The glassfish console shows this when I try to get data from the database:
(Tosad is the name of the project/course)
[2016-01-08T15:23:07.004+0000] [glassfish 4.1] [INFO] [] []
[tid: _ThreadID=43 _ThreadName=Thread-8] [timeMillis: 1452266587004] [levelValue: 800] [[
[EL Severe]: ejb: 2016-01-08 15:23:07.004--ServerSession(1585495182)--
Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd):
org.eclipse.persistence.exceptions.ValidationException
Exception Description: Cannot acquire data source [TOSAD].
Internal Exception: javax.naming.NamingException: Lookup failed for 'TOSAD' in SerialContext[
myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl,
java.naming.factory.url.pkgs=com.sun.enterprise.naming}
[Root exception is javax.naming.NameNotFoundException: TOSAD not found]]]
Hibernate.cfg.xml (I replaced some info for safety purposes)
<?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.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#ondora02.hu.nl:PORT:COURSE</property>
<property name="hibernate.connection.username">USERNAME</property>
<property name="hibernate.connection.password">PASSWORD</property>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
package Service;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class HibernateUtil {
private static String orclcfg = "nl.hu.ict.jpa.oracle";
private static String mysqlcfg = "nl.hu.ict.jpa.mysql";
private static boolean mysql = false;
private static String dbcfg = orclcfg;
private static final EntityManagerFactory entityManagerFactory;
//entityManagerFactory = Persistence.createEntityManagerFactory("nl.hu.ict.jpa.oracle" );
static {
try {
if (!mysql) {
dbcfg = orclcfg;
}
entityManagerFactory = Persistence.createEntityManagerFactory(dbcfg);
} catch (Throwable th) {
System.err.println("Initial EntityManagerFactory creation failed" + th);
throw new ExceptionInInitializerError(th);
}
}
public static EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
}

The error message is somewhat clear. The JNDI resource named TOSAD cannot be located on your remote deployed server. Make sure it is configured on the remote server like you likely have done on your local machine.

Related

Spring Boot - Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration'

I have spring boot application setup. Now I need to add Spring JDBC Template to it. While doing this, I am facing below exception.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'XXX': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.jdbc.core.JdbcTemplate com..XXX.jdbcTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "LOCAL" are currently active).
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "LOCAL" are currently active).
Below is the code.
#Service
public class XXX {
#Autowired
JdbcTemplate jdbcTemplate;
public void testDataSource() {
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from C_MASTER");
System.out.println("list : " + list);
}
}
Java Config
#Configuration
#ComponentScan
#EnableTransactionManagement
public class DAODataServiceManagerConfiguration {
#Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:#g9u1769.houston.hpecorp.net:1525:ODSDBD");
dataSource.setUsername("Solid_batch");
dataSource.setPassword("solid_batch123");
return dataSource;
}
}
As spring boot looks for application.properties, I have added that too in the resources directory.
appliation.properties.
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:#g9u1769.houston.hpecorp.net:1525:ODSDBD
spring.datasource.username=Solid_batch
spring.datasource.password=solid_batch123
spring.datasource.initialize=true
It is unable to build the application. Correct me if I am doing anything wrong.
You are missing ojdbc jar in your project classpath, follow below steps to download, install and use it as a dependency:
Download ojdbc6.jar from here.
Install it, running command -
mvn install:install-file -Dfile={Path/to/your/ojdbc.jar} -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar
For jar version, extract the jar file and check the Implementation-Version in MANIFEST.MF, for instance:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.6.5
Created-By: 1.5.0_51-b10 (Sun Microsystems Inc.)
Implementation-Vendor: Oracle Corporation
Implementation-Title: JDBC
Implementation-Version: 11.2.0.4.0
Repository-Id: JAVAVM_11.2.0.4.0_LINUX.X64_RELEASE
Specification-Vendor: Sun Microsystems Inc.
Specification-Title: JDBC
Specification-Version: 4.0
Main-Class: oracle.jdbc.OracleDriver
sealed: true
Name: oracle/sql/converter/
Sealed: false
Name: oracle/sql/
Sealed: false
Name: oracle/sql/converter_xcharset/
Sealed: false
Name: oracle/replay/driver/
Sealed: false
Add as a dependency in the project, as follows:
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
</dependency>
Use jdbctemplate by extends JdbcDaoSupport .
By it programmer not concern about the open and close the connection.
Use commons-dbcp2-2.1.1.jar and commons-pool2-2.4.2.jar for use dbcp2 because dbcp2 support Connection pooling.
It's a technique to allow multiple clinets to make use of a cached set of shared and reusable connection objects providing access to a database
public class XXX extends JdbcDaoSupport {
public void testDataSource() {
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from C_MASTER");
System.out.println("list : " + list);
}
}
In spring.xml write
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/database_name" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
<bean id="xXX" class="your_package_name.XXX">
<property name="dataSource" ref="dataSource" />
</bean>
I have gone through spring boot reference document. I came to know that if we are using (H2, HSQL or Derby) databases then we don't require application.properties.
If the project is having Oracle database, then application.properties should be updated. In my case I have updated the properties file.
So I have updated only following things, then it worked properly.
pom.xml
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
configuration file
#Configuration
public class DaoConfig {
#Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
dataSource.setUrl("xxx");
dataSource.setUsername("xxx");
dataSource.setPassword("xxx");
return dataSource;
}
#Bean
public JdbcTemplate getJdbcTemplate() {
return new JdbcTemplate(getDataSource());
}
I hope this might help someone.
Thanks #ChrisThompson and #Arpit

CDI (Weld), DeltaSpike, Tomcat and persistence.xml

I am setting up a new project using Tomcat, Weld (for CDI) and DeltaSpike (Data, JPA and JSF modules)
I have reached the point now where I am trying to create a JPA repository (backed by Hibernate) by following the directions in the DeltaSpike documentation (http://deltaspike.apache.org/documentation/data.html).
I am struggling to hook up the persistence unit in the way the documentation describes as my EntityManagerFactory object is always null
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
public class EntityManagerProducer {
#PersistenceUnit(unitName = "srdPersistenceUnit")
private EntityManagerFactory emf;
#Produces // you can also make this #RequestScoped
public EntityManager create() {
return emf.createEntityManager();
}
public void close(#Disposes EntityManager em) {
if (em.isOpen()) {
em.close();
}
}
}
I have created a persistence.xml file which is in the /META-INF/ directory of the jar file that contains my service/data layer
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="srdPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>java:comp/env/jdbc/srdDCP</non-jta-data-source>
<properties>
</properties>
</persistence-unit>
</persistence>
I was previously using Spring to handle dependency injection and the JPA stuff which worked fine so I know my data source is set up correctly as a Tomcat JNDI resource.
Now however I see this exception (suggesting that the EntityManagerFactory is not being injected)
Caused by: java.lang.NullPointerException
at testproj.data.entity.EntityManagerProducer.create(EntityManagerProducer.java:18)
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:497)
at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:88)
at org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:78)
at org.jboss.weld.injection.producer.ProducerMethodProducer.produce(ProducerMethodProducer.java:95)
at org.jboss.weld.injection.producer.AbstractMemberProducer.produce(AbstractMemberProducer.java:167)
at org.jboss.weld.bean.AbstractProducerBean.create(AbstractProducerBean.java:183)
at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:69)
at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.get(ContextualInstanceStrategy.java:101)
at org.jboss.weld.bean.ContextualInstance.get(ContextualInstance.java:50)
at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:761)
at org.jboss.weld.bean.builtin.InstanceImpl.getBeanInstance(InstanceImpl.java:179)
at org.jboss.weld.bean.builtin.InstanceImpl.get(InstanceImpl.java:99)
at org.apache.deltaspike.data.impl.handler.EntityManagerLookup.lookupFor(EntityManagerLookup.java:58)
at org.apache.deltaspike.data.impl.handler.QueryHandler.createContext(QueryHandler.java:104)
at org.apache.deltaspike.data.impl.handler.QueryHandler.invoke(QueryHandler.java:77)
I suspect I have missed something in the setting up of the persistence unit.
What more do I need to do to create a valid persistence unit backed by hibernate jpa linked to my datasource?

Java EE Persistence WELD-001408 when deploying on wildfly

I have a problem, when I want to deploy my application on wildfly.
This is my persistence:
<persistence-unit name="jws" transaction-type="JTA">
<class>lv.lavloz.merrill.generator.v1.model.ID</class>
<jta-data-source>java:jboss/datasources/MySQL/JWSDS</jta-data-source>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
The connection url for the jndi java:jboss/datasources/MySQL/JWSDS is jdbc:mysql://localhost:3306/db.
And this is the ejb :
#Stateless
public class GeneratorBean {
#PersistenceContext(unitName = "jws")
private EntityManager em;
...
}
When I want to deploy my application to wildfly, I get the error message
java.lang.Exception: {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"jws_ear.ear\".WeldStartService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"jws_ear.ear\".WeldStartService: Failed to start service
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type ParamConverterFactory with qualifiers #Default
at injection point [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] #Inject public org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorFactory(ParamConverterFactory)
at org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorFactory.<init>(MultivaluedParameterExtractorFactory.java:0)
WELD-001474: Class org.glassfish.jersey.server.internal.inject.ParamConverterFactory is on the classpath, but was ignored because a class it references was not found: org.glassfish.hk2.api.ServiceLocator from [Module \"deployment.jws_ear.ear:main\" from Service Module Loader].
"}}
What to do?
This does not seem to be related to JPA at all.
Your error message referring to org.glassfish.jersey.server.internal indicates that your application has a dependency on Jersey.
Are you trying to port an application from GlassFish to WildFly? If so, you should eliminate all dependencies on Jersey and only use the JAX-RS APIs, or WildFly's JAX-RS implementation RESTEasy.
Jersey is not contained in WildFly.

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.

hibernate buildSessionFactory ClassFormatError:

ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/InheritanceType
I got this error when try to build sessionFactory
my hibernate.cfg.xml file :
<?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.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">mateusz</property>
<property name="hibernate.connection.password">mateusz123</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/carpool</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="org.mathew.data.User"></mapping>
</session-factory>
</hibernate-configuration>
my HibernateUtil class:
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
StackTrace:
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.mathew.hibutil.HibernateUtil.buildSessionFactory(HibernateUtil.java:19)
at org.mathew.hibutil.HibernateUtil.<clinit>(HibernateUtil.java:8)
at org.mathew.mysql.MySqlQueries.<init>(MySqlQueries.java:16)
at org.mathew.test.AppMain.main(AppMain.java:8)
Caused by: java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/InheritanceType
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at org.hibernate.cfg.InheritanceState.extractInheritanceType(InheritanceState.java:51)
at org.hibernate.cfg.InheritanceState.<init>(InheritanceState.java:21)
at org.hibernate.cfg.AnnotationBinder.buildInheritanceStates(AnnotationBinder.java:2146)
at org.hibernate.cfg.AnnotationConfiguration.processArtifactsOfType(AnnotationConfiguration.java:492)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:277)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1319)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:915)
at org.mathew.hibutil.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
... 3 more
My libraries:
cglib
commons-collections
commons-logging
dom4j
hibernate3
hibernate-annotations
hibernate-commons-annotations
hibernate-core
java-api-6.0
javassist
jta
log4j
mysql-connector-java
persistence-api
slf4j
slf4j-log4j
I can't upload image :)
I would be thankfull if anybody can help.
THANKS! :)
You seem to be managing your dependencies manually, you should really be using a dependency manager (maven, ivy with ant, etc.) to be sure you get the correct dependencies (all the libs in their expected version). Since you don't specify the versions of the libraries you're using, there are several possible problems:
Incompatible version of persistence-api with hibernate
Incompatible mix of hibernate jars: you apparently have a hibernate3 jar along with hibernate-core, that doesn't seem right. It looks like a old version of Hibernate mixed with more recent jars. So classes that only exist in the recent version might be accessing classes from the old one, if the jar comes first in the classpath.

Categories