we're using spring, hibernate and hsql to persist a simple user entity. We always get the error "table not found". Do you have any idea what this could be? It seems like the table is not generated or the hsql database is not running at all.
Regards,
G.
#Entity
#Table (name="USER")
public class User {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="ID")
private Long id;
#Column(name="NAME", length = 100, nullable = false)
private String name;
public User(){}
//getters and setters ...
by this dao class:
package de.hsrm.mediathek;
import java.util.List;
public class UserDao implements IUserDao{
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(final HibernateTemplate hibernateTemplate){
this.hibernateTemplate = hibernateTemplate;
}
#Transactional
public void store(final User user){
hibernateTemplate.saveOrUpdate(user);
}
#Transactional
public void delete(final Long userId){
final User user = (User) hibernateTemplate.get(User.class, userId);
hibernateTemplate.delete(user);
}
#Transactional(readOnly = true)
public User findById(final Long userId){
return (User) hibernateTemplate.get(User.class, userId);
}
#Transactional(readOnly = true)
public List<User> findAll(){
return hibernateTemplate.find("from User");
}
}
Configuration 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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<tx:annotation-driven/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:mem:mediathekdb" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>de.hsrm.mediathek.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.hbm2dll.auto">create-drop</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.connection.pool_size">10</prop>
<prop
key="hibernate.cache.provider_class">
org.hibernate.cache.HashtableCacheProvider</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="userDao" class="de.hsrm.mediathek.UserDao">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Interceptor for hibernate calls to be able to create and close sessions
<bean id="hibernateInterceptor"
class="org.springframework.orm.hibernate3.HibernateInterceptor">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>
-->
</beans>
Error LOG:
Caused by: java.sql.SQLException: Table not found in statement [insert into User (ID, NAME) values (null, ?)]
at org.hsqldb.jdbc.Util.throwError(Unknown Source)
at org.hsqldb.jdbc.jdbcPreparedStatement.<init>(Unknown Source)
at org.hsqldb.jdbc.jdbcConnection.prepareStatement(Unknown Source)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:528)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:95)
at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:30)
... 63 more
The problem is that the property "hbm2dll" is wrongly spelled. It should be "hbm2ddl":
It is:
<prop key="hibernate.hbm2dll.auto">create-drop</prop>
It should be:
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
It's also better to keep an eye on logs for any other errors, as I had a similar problem and found out that create table statement was failing for HSQLDB's DDL generated by Hibernate and Hibernate was silently swallowing it
2011-06-09 10:48:30,722 [main] ERROR org.hibernate.tool.hbm2ddl.SchemaExport - Wrong data type: ALERT_ID in statement [create table ACCOUNT_ALERT (ALERT_ID numeric generated by default as identity (start with 1)]
Later when I changed the following
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="ALERT_ID")
private BigInteger alertId;
to
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name="ALERT_ID")
private BigInteger alertId;
it worked perfectly.
I'd suggest trying to run HSQLDB in server mode using:
java -classpath hsqldb.jar org.hsqldb.server.Server
Check that it's running using Database manager:
java -classpath hsqldb.jar org.hsqldb.util.DatabaseManagerSwing
Next, change your Hibernate URL, so it uses server mode HSQLDB:
<property name="url" value="jdbc:hsqldb:mediathekdb" />
I've had success using this method. It's possible that create-drop doesn't work properly when using a memory only instance.
Related
I am trying to call on a stored procedure from a db2 database using hibernate's entity manager and return the results as an object. I am using the #NamedStoredProcedureQuery annotation which does not seem to be found by hibernate. I am getting the error: "No #NamedStoredProcedureQuery was found with that name : Create_Division". Any ideas would be great.
beans:
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="demoJPAUnit" />
<property name="packagesToScan">
<list>
<value>com.merchantBoarding.db2.queryObjects</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.archive.autodetection">class,hbm</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.DB2Dialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
Query output object:
#NamedStoredProcedureQuery(
name="Create_Division",
procedureName="MD.PMDBD017",
resultClasses = {CreateDivisionResult.class},
parameters={
#StoredProcedureParameter(name="IN_ENTY",mode=ParameterMode.IN,type=Integer.class),
#StoredProcedureParameter(name="IN_PARNT_ENTY",mode=ParameterMode.IN,type=Integer.class),
#StoredProcedureParameter(name="IN_ACTION",mode=ParameterMode.IN,type=String.class),
#StoredProcedureParameter(name="IN_ENTY_XREF",mode=ParameterMode.IN,type=String.class),
#StoredProcedureParameter(name="OUT_ENTY",mode=ParameterMode.OUT,type=Integer.class),
#StoredProcedureParameter(name="OUT_ID",mode=ParameterMode.OUT,type=String.class),
#StoredProcedureParameter(name="OUT_ENTY_XREF",mode=ParameterMode.OUT,type=String.class),
#StoredProcedureParameter(name="OUT_SQLCODE",mode=ParameterMode.OUT,type=Integer.class),
#StoredProcedureParameter(name="OUT_STATUS",mode=ParameterMode.OUT,type=String.class),
#StoredProcedureParameter(name="OUT_ERRORTEXT",mode=ParameterMode.OUT,type=String.class),
}
)
public class CreateDivisionResult implements Serializable {
#Id
public String OUT_ENTY;
public String OUT_ID;
public String OUT_ENTY_XREF;
public String OUT_SQLCODE;
public String OUT_STATUS;
public String OUT_ERRORTEXT;
}
DAO code:
StoredProcedureQuery query = manager.createNamedStoredProcedureQuery("Create_Division");
query.setParameter("IN_ENTY", 111);
query.setParameter("IN_PARNT_ENTY", 11111);
query.setParameter("IN_ACTION", "CREATE");
query.setParameter("IN_ENTY_XREF", "ED");
List<CreateDivisionResult> results = query.getResultList();
EDIT:
So I added #Entity and that did fix the original error, but the output parameters still aren't mapping to the CreateDivisionResult object. I can only get each indiviual field with query.getOutputParameterValue. Is this just a restriction of JPA?
#NamedStoredProcedureQuery should be applied to Entity class or mapped class
Seems you are missing the #Entity in your 'CreateDivisionResult'
I have this exception :
org.hibernate.MappingException: persistent class not known:
java.lang.Long
I'm using Hibernate 5.1.0.Final and spring-orm 4.2.4.RELEASE
My spring configuration file (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="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/ecollection" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="hibernateAnnotatedSessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.ecollection.model.Adresse</value>
<value>com.ecollection.model.Utilisateur</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="utilisateurDao" class="com.ecollection.dao.UtilisateurDaoImpl">
<property name="sessionFactory" ref="hibernateAnnotatedSessionFactory" />
</bean>
<bean id="adresseDao" class="com.ecollection.dao.AdresseDaoImpl">
<property name="sessionFactory" ref="hibernateAnnotatedSessionFactory" />
</bean>
And I have two MySQL tables, User and Address.
User = Id, Name and Firstname
Address = Id, Street, City and UserId
for UserId in my Address entitybean, I'm doing this :
#OneToOne
#JoinColumn(name="id")
public Long getIdUtilisateur() {
return idUtilisateur;
}
You can not use a non entity as a target for OneToOne or JoinColumn, as you did here:
#OneToOne
#JoinColumn(name="id")
public Long getIdUtilisateur() {
return idUtilisateur;
}
Instead you can use this approach for mapping Utilisateur and Address relationship:
#OneToOne
#JoinColumn(name="id")
public Utilisateur getUtilisateur() {
return utilisateur;
}
Of course, Utilisateur should be an entity:
#Entity
public class Utilisateur { ... }
I was running my unit tests directly with the targetted Database which is : Oracle 10g and i was asked to run them under H2 Database.
So, after generating the differents SQL scripts and configured the H2 database (through XML config. with Spring), i realized that some of my tests failed whereas some of them passed...
I have the following view (a view of a view) which returns different columns :
CREATE OR REPLACE FORCE VIEW ##.VIEW_OLB_SAT_COVERAGE
(
SAT_CODE,
ORBITAL_POSITION,
COVERAGE_DOWN,
COVERAGE_UP
)
AS
SELECT DISTINCT sat_code,
orbital_position,
coverage_down,
coverage_up
FROM ##.VIEW_OLB_TXP_COVERAGE
ORDER BY sat_code ASC;
The view "VIEW_OLB_TXP_COVERAGE" is the following :
CREATE OR REPLACE FORCE VIEW ##.VIEW_OLB_TXP_COVERAGE
(
SAT_CODE,
ORBITAL_POSITION,
TXP_NO,
COVERAGE_DOWN,
COVERAGE_UP,
POLARIZATION_DOWN,
POLARIZATION_UP
)
AS
SELECT DISTINCT ##.OLB_AVAILABLE_TXP.SAT_CODE,
###.SAT_DEP.ORBIT_LOC / 3600 ORBITAL_POSITION,
##.OLB_AVAILABLE_TXP.TXP_NO,
###.TXP.CUR_DN_COVERAGE COVERAGE_DOWN,
###.TXP.CUR_UP_COVERAGE COVERAGE_UP,
###.TXP.TXP_DN_POL,
###.TXP.TXP_UP_POL
... The rest is omitted for clarity
The Hibernate entities are the following :
#Component(value = "viewOlbSatCoverage")
#Scope("prototype")
#Entity
#Table(name = "VIEW_OLB_SAT_COVERAGE", schema = "##")
public class ViewOlbSatCoverage implements Serializable {
private static final long serialVersionUID = -6728959649786852446L;
#Id
private ViewOlbSatCoverageId viewOlbSatCoverageId;
public ViewOlbSatCoverageId getViewOlbSatCoverageId() {
return viewOlbSatCoverageId;
}
public void setViewOlbSatCoverageId(ViewOlbSatCoverageId viewOlbSatCoverageId) {
this.viewOlbSatCoverageId = viewOlbSatCoverageId;
}
#Override
public String toString() {
return "ViewOlbSatCoverage : [viewOlbSatCoverageId=" + viewOlbSatCoverageId == null ? "null"
: viewOlbSatCoverageId.toString() + "]";
}
}
#Component(value = "viewOlbSatCoverageId")
#Scope("prototype")
#Embeddable
public class ViewOlbSatCoverageId implements Serializable {
private static final long serialVersionUID = 2822316442843031126L;
#Column(name = "COVERAGE_DOWN")
private String coverageDown;
#Column(name = "COVERAGE_UP")
private String coverageUp;
#Column(name = "SAT_CODE")
private String satCode;
#Column(name = "ORBITAL_POSITION")
private BigDecimal orbitalPosition;
public ViewOlbSatCoverageId() {
}
public ViewOlbSatCoverageId(String satCode, BigDecimal orbitalPosition, String coverageDown, String coverageUp) {
setSatCode(satCode);
setOrbitalPosition(orbitalPosition);
setCoverageDown(coverageDown);
setCoverageUp(coverageUp);
}
// Getters, setters omitted for clarity ...
}
As I mentionned, the targetted database is Oracle 10g and all works fine with it (when the app is running).
But when I run H2 database for unit testing purpose, the following method ( findDistinctAllOrbitalPositions) doesn't work :
#Repository
public class ViewOlbSatCoverageDaoImpl extends GenericDaoImpl<ViewOlbSatCoverage> implements ViewOlbSatCoverageDao {
public ViewOlbSatCoverageDaoImpl() {
setGenericClass(ViewOlbSatCoverage.class);
setDaoLogger(ViewOlbSatCoverageDaoImpl.class);
}
#Override
#SuppressWarnings("unchecked")
public List<BigDecimal> findDistinctAllOrbitalPositions() {
Query query = sessionFactory.getCurrentSession().createQuery(
"select distinct(viewOlbSatCoverageId.orbitalPosition) from " + genericClass.getSimpleName()
+ " order by viewOlbSatCoverageId.orbitalPosition asc"); // genericClass is ViewOlbSatCoverage
return query.list();
}
}
As you can see, i'm using HQL but also the Criteria API.
When i launch maven from command line :
mvn clean -Dtest=ViewOlbSatCoverageDaoImplTestCase test
It gives me the following :
Caused by: org.h2.jdbc.JdbcSQLException: Column "VIEWOLBSAT0_.ORBITAL_POSITION" not found; SQL state
ment:
select distinct viewolbsat0_.ORBITAL_POSITION as col_0_0_ from ##.VIEW_OLB_SAT_COVERAGE viewolbsat0_
order by viewolbsat0_.ORBITAL_POSITION asc [42122-190]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:147)
at org.h2.expression.Alias.optimize(Alias.java:51)
at org.h2.command.dml.Select.prepare(Select.java:835)
at org.h2.command.Parser.prepareCommand(Parser.java:246)
at org.h2.engine.Session.prepareLocal(Session.java:460)
at org.h2.engine.Session.prepareCommand(Session.java:402)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188)
at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:72)
at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:276)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler.continueInvocation(Connec
tionProxyHandler.java:138)
... 64 more
Here is a sample of my applicationContext-test.xml :
<jdbc:embedded-database id="h2TestDataSource" type="H2"/>
<jdbc:initialize-database data-source="h2TestDataSource">
<jdbc:script location="classpath:com/eutelsat/olb/sql/create/views/VIEW_OLB_SAT_COVERAGE.sql" />
<jdbc:script location="classpath:com/eutelsat/olb/sql/create/views/VIEW_OLB_TXP_COVERAGE.sql" />
<!-- Other .sql files omitted for clarity -->
</jdbc:initialize-database>
<!-- Connection pool -->
<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="org.h2.Driver" />
<property name="jdbcUrl" value="jdbc:h2:mem:h2TestDataSource;INIT=RUNSCRIPT FROM 'com/eutelsat/olb/sql/create/schemas/INIT.sql'" />
<property name="user" value="sa" />
<property name="password" value="" />
<property name="acquireIncrement" value="1" />
<property name="minPoolSize" value="1" />
<property name="maxPoolSize" value="5" />
<property name="maxIdleTime" value="30" />
<property name="maxIdleTimeExcessConnections" value="10" />
<property name="numHelperThreads" value="3" />
<property name="unreturnedConnectionTimeout" value="0" />
</bean>
<!-- Session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="h2TestDataSource" />
<property name="packagesToScan" value="com.eutelsat.olb.server.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">none</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
<prop key="hibernate.use_outer_join">true</prop>
<prop key="hibernate.order_inserts">true</prop>
<prop key="hibernate.order_updates">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="format_sql">true</prop>
<prop key="hibernate.id.new_generator_mappings">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
I have read a lot of things but I can't find what the problem is (incorrect SQL script which needs to be adapted to fit in H2 database or maybe an H2 database config. with column alias matters ?).
NB : schemas have been obfuscated.
Thanks in advance for pointers.
I've found a solution to my problem.
The SQL scripts (some of them were omitted in the sample posted in SOF) which were declared in my "applicationContext-test.xml" file were not well ordered resulting in a view with a INVALID status.
-> Resulting in generated SQL query done by Hibernate complaining that some tables and / or columns were'nt found.
I've found the problem (and also the solution) thanks to the excellent H2 web server allowing me to view in memory data. In the SCHEMA_INFORMATION section, I saw VIEWS and when clicking on it, I saw STATUS = INVALID.
In order to add an H2 web server using Spring XML config, you can easily add this :
<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
<constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,9992"/>
</bean>
<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
<constructor-arg value="-web,-webAllowOthers,-webPort,8882"/>
</bean>
Do not forget to add a depends-on attribute valued to "h2Server" (so : depends-on="h2Server") to you datasource bean, otherwise it will not work as expected !
I am trying to fetch data from database using hibernate annotation but it is not working as my expected. I have a two table Employee and Department. the java code is as below :
Employee class
#Entity
#Table(name = "EMPLOYEE")
public class EmployeeBO {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "EMPID")
private int empId;
#Column(name = "EMPNAME")
private String empName;
#Column(name = "SALARY")
private int empSalary;
#Column(name = "EMPADDRESS")
private String empAddress;
#Column(name = "EMPAGE")
private int empAge;
#Column(name = "DEPTID")
private Integer deptId;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="DEPTID", nullable = true, insertable = false, updatable = false)
private DepartmentBO departmentBO;
// getter and setter
}
Department class :
#Entity
#Table(name = "DEPARTMENT")
public class DepartmentBO {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "DEPTID")
private int deptid;
#Column(name = "DEPTNAME")
private String deptName;
// getter and setter.
}
spring-servlet.xml file :
<?xml version="1.0" encoding="UTF-8"?>
<!--?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.web"></context:component-scan>
<context:property-placeholder location="file:D:/EasyProp/db.properties" ignore-unresolvable="false"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="basicDataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driver.classname}" />
<property name="url" value="${driver.url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- <property name="initialSize" value="10"/> -->
<!-- <property name="maxActive" value="25"/> -->
<!-- <property name="maxIdle" value="25"/> -->
<!-- <aop:scoped-proxy/> -->
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
<!-- <bean id="dbUtil" class="com.web.utility.OnLoadStartUp" init-method="initialize">
<property name="dataSource" ref="basicDataSource" />
</bean> -->
<!-- <bean id="loadOnStartUp" class="com.web.utility.LoadOnStartUp">
<property name="baseService" ref="baseService"></property>
</bean> -->
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="basicDataSource" />
<property name="annotatedClasses">
<list>
<value>com.web.bo.EmployeeBO</value>
<value>com.web.bo.DepartmentBO</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hmb2ddl.auto">validate</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.jdbc.fetch_size">10</prop>
<prop key="hibernate.jdbc.batch_size">25</prop>
<prop key="hibernate.jdbc.batch_versioned_data">true</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.default_batch_fetch_size">8</prop>
<prop key="hibernate.order_updates">true</prop>
<prop key="hibernate.connection.release_mode">on_close</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">true</prop>
<prop key="hibernate.bytecode.provider">javassist</prop>
</props>
</property>
</bean>
</beans>
when i trying to fetch all data from employee and department table but it only returns the data from employee table my code for hit hql query as below :
List<EmployeeBO> empList = null;
empList = sessionFactory.getCurrentSession().createQuery("From "+employeeBO.getClass().getName()).list();
above query is hit as below on database.
select employeebo0_.EMPID as EMPID0_, employeebo0_.DEPTID as DEPTID0_, employeebo0_.EMPADDRESS as EMPADDRESS0_, employeebo0_.EMPAGE as EMPAGE0_, employeebo0_.EMPNAME as EMPNAME0_, employeebo0_.SALARY as SALARY0_ from EMPLOYEE employeebo0_
But i want all data of the employee table and department table using Eager fetching.
It works as expected. The EmployeeBO contains a DepartmentBO. The DepartmentBO will automatically be filled the moment you access it.
This is not true, if the Hibernate session containing the EmployeeBO has ended. Then the EmployeeBO is transient and hibernate will not fetch the missing object.
To enforce filling the DepartmentBO, you can add a fetch clause to your hql code. But that is not lazy fetching any more.
The HQL
from EmployeeBO join fetch EmployeeBO.department
should do the job (replace the EmployeeBO with the actual entity name).
See here in the hibernate docs: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html and for the fetching strategies here https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/performance.html#performance-fetching
From the comments, you actually want eager fetching on the relationship, so you need to declare the fetchtype to be eager:
#ManyToOne(fetch=FetchType.EAGER)
should fix it. Adding another doc here: https://docs.oracle.com/javaee/6/api/javax/persistence/ManyToOne.html
There are two ways to do this:
1) use EAGER fetch type
2) call getDepartmentBO() on each employee after you get the employee
I think you have missed the anotation for lazy loading.
You have to use (fetch=FetchType.LAZY) on a association which you want to lazy load
Hibernate by default has Lazy loading. i.e. it would not fetch the data of another table. In you case if you want the data of department table, you will have to call getter of departmentBO if you are in hibernate session. Note: it will fire another query. else you can also use
Hibernate.initialize(entity.getdepartmentBO())
If you want by default to get the department data. use the following code
#ManyToOne(fetch=FetchType.EAGER)
I am newbie to h2 database.i created the sessionfactory like below.
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:~/selva;DB_CLOSE_DELAY=-1" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.selva.meetinghall.domain.My</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
My.java
#Entity
#Table(name="my")
#Repository
public class My implements java.io.Serializable {
private static final long serialVersionUID = -1798070786993154670L;
#Id
#Column(name ="Id")
private int id;
#Column(name ="Name")
private String name;
//getter and setter
}
Dao :
Session session=sessionfactory.openSession();
Transaction tx=session.beginTransaction();
My my=new My();
my.setId(1);
my.setName("selva");
session.save(my);
tx.commit();
I got the error like below.
Hibernate: insert into my (Name, Id) values (?, ?)
2015-01-20 18:41:02,911 WARN org.hibernate.util.JDBCExceptionReporter.logExceptions:77 - SQL Error: 42102, SQLState: 42S02
2015-01-20 18:41:02,911 ERROR org.hibernate.util.JDBCExceptionReporter.logExceptions:78 - Table "MY" not found; SQL statement:
insert into my (Name, Id) values (?, ?) [42102-185]
2015-01-20 18:41:02,913 ERROR org.hibernate.event.def.AbstractFlushingEventListener.performExecutions:301 - Could not synchronize database state with session
org.hibernate.exception.SQLGrammarException: could not insert: [com.selva.meetinghall.domain.My]
The above code works for mssql persistent database.But does not work in h2 database.What's wrong with my approach?
Is Querying is different for inmemory and persistent databse?
Any help will be greatly appreciated!!