I've created custom spring scope using code found in this link which enables the use of view scoped Spring managed bean similar to that of JSF2 #ViewScoped.
When user presses the Submit button the following takes place:
- Backbean AA (#Scope(value="view") calls injected #Service BB
- #Service BB calls DAO class CC
- CC is #Transactional(readOnly = true) and has sessionFactory injected
private SessionFactory sessionFactory;
//inject sessionGactory
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
- in CC i set the #Transactional(readOnly = false, propagation = Propagation.REQUIRED)
for functions such as save/delete/saveOrUpdate
The Hibernate mapping concerning this class are:
RegUser.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.testApp.hibernate.RegUser" table="reg_users" schema="dbo" catalog="devDB">
<id name="userPk" type="java.lang.Long">
<column name="userPK" />
<generator class="identity" />
</id>
<property name="firstname" type="java.lang.String">
<column name="firstname" length="25" not-null="true" />
</property>
<property name="lastname" type="java.lang.String">
<column name="lastname" length="50" not-null="true" />
</property>
<set name="UserVsOrderses" inverse="true">
<key>
<column name="userPK" not-null="true" />
</key>
<one-to-many class="com.testApp.hibernate.UserVsOrders" />
</set>
</class>
</hibernate-mapping>
UserVsOrders.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.testApp.hibernate.custOrders" table="custOrders" schema="dbo" catalog="devDB">
<composite-id name="id" class="com.testApp.hibernate.custOrdersId">
<key-property name="userPk" type="java.lang.Long">
<column name="userPK" />
</key-property>
<key-property name="OrderPk" type="java.lang.Long">
<column name="OrderPK" />
</key-property>
</composite-id>
<many-to-one name="RegUser" class="com.testApp.hibernate.RegUser" update="false" insert="false" fetch="select">
<column name="userPK" not-null="true" />
</many-to-one>
<many-to-one name="Order" class="com.testApp.hibernate.Order" update="false" insert="false" fetch="select">
<column name="OrderPK" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
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.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.testApp" />
<context:annotation-config />
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view">
<bean class="com.testApp.util.ViewScope" />
</entry>
</map>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver">
</property>
<property name="url" value="jdbc:jtds:sqlserver://localhost:1433/devDB">
</property>
<property name="username" value="blabla"></property>
<property name="password" value="blabla"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">20</prop>
<prop key="hibernate.c3p0.idle_test_period">300</prop>
<prop key="hibernate.c3p0.timeout">1800</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
<prop key="c3p0.acquire_increment">1</prop>
<props>
</property>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
...
<!-- some other beans declared below -->
...
<!-- all the Mapping Resource -->
</beans>
My Problem is that one first form submit all is well, but on the next form submit i get:
failed to lazily initialize a collection, no session or session was closed
viewId=/page/regNewCust.xhtml
location=C:\repo\dev\WebRoot\nz\regNewCust.xhtml
phaseId=PROCESS_VALIDATIONS(3)
Caused by:
org.hibernate.LazyInitializationException - failed to lazily initialize a collection, no session or session was closed
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:394)
The page works fine if i set bean scope as #Scope(value='request')
I have tried adding the folloiwng to web.xml but it didn't help:
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
I've also tried adding <set name="UserVsOrderses" inverse="true" fetch="join"> which didn't help either.
Can anyone point of what i'm doing wrong and how i can fix the issue?
Found the solution here:
Stackoverflow link
I needed to add
<f:attribute name="collectionType" value="java.util.HashSet" />
to all the <h:selectManyListbox>
Related
My project is using hibernate3 along with spring 2.5. Now I am migrating it to Spring5 and hibernate5 with JPA.
I have hbm.xml for my entities using hibernate-mapping. After migration I get the error:
Caused by: org.hibernate.AssertionFailure: Unable to locate referenced
entity mapping [com.mycompany.common.admin.Entity1] in order to
process many-to-one FK : com.mycompany.common.admin.Entity2
The Entity2 has many-to-one FK with reference of Entity1
The code for entitymanagerfactory in applicationContext.xml:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource">
<ref bean="myDataSource"/>
</property>
<property name="packagesToScan" value="com.mycompany"/>
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
<property name="persistenceUnitPostProcessors">
<list>
<bean
class="org.springframework.data.jpa.support.ClasspathScanningPersistenceUnitPostProcessor">
<constructor-arg index="0" value="com.mycompany" />
<property name="mappingFileNamePattern" value="classpath*:com/**/*hbm.xml" />
</bean>
</list>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
The hbm.xml for Entity2 is as below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.mycompany.common.admin.Entity2" table="entity2">
<id column="id" name="ID">
<generator class="uuid"/>
</id>
<property name="name" type="string">
<column name="name"/>
</property>
<many-to-one class="com.mycompany.common.admin.Entity1" name="entity1" not-null="true"/>
</class>
</hibernate-mapping>
Error stack trace:
Caused by: org.hibernate.AssertionFailure: Unable to locate referenced entity mapping [com.mycompany.common.admin.Entity1] in order to process many-to-one FK : com.mycompany.common.admin.Entity2.entity1
at org.hibernate.boot.model.source.internal.hbm.ModelBinder$ManyToOneColumnBinder.doSecondPass(ModelBinder.java:4066)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1696)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1652)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:287)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1758)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1695)
Please let me know what am I missing here.
I recently moved from Hibernate to JPA. Now I notice two things in my code.
Methods in my services do not need #Transactional anymore to perform insertion to the database.
Transaction never get rolled back even if there's any exception.
applicationContext.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:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.myapp.service, com.myapp.batch,com.myapp.auth" />
<!-- Configure the data source bean -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="dataSourceProperties" >
<props>
<prop key="url">jdbc:mysql://localhost:3306/app?zeroDateTimeBehavior=convertToNull</prop>
<prop key="user">user</prop>
<prop key="password">pass</prop>
</props>
</property>
<property name="dataSourceClassName"
value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" />
</bean>
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
<constructor-arg ref="hikariConfig" />
</bean>
<!-- Create default configuration for Hibernate -->
<bean id="hibernateJpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
<!-- Configure the entity manager factory bean -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.myapp.persist" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.c3p0.timeout">100</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean class="org.springframework.jdbc.datasource.init.DataSourceInitializer"
depends-on="entityManagerFactory">
<property name="dataSource" ref="dataSource" />
<property name="databasePopulator">
<bean
class="org.springframework.jdbc.datasource.init.ResourceDatabasePopulator">
<property name="scripts" value="classpath:initial_data.sql" />
<property name="continueOnError" value="true" />
</bean>
</property>
</bean>
<jpa:repositories base-package="com.myapp.repositories"
entity-manager-factory-ref="entityManagerFactory" />
<!-- Enable annotation driven transaction management -->
<tx:annotation-driven />
<task:annotation-driven />
</beans>
NetworkService.java
#Service
public class AdminUserManagementService {
#Autowired
UserRepository userRepository;
#Autowired
UserService userService;
#Autowired
RequestRegisterHistoryRepository requestRegisterHistoryRepository;
#Autowired
#Transactional(rollbackFor=Exception.class)
public User saveUser(UserBO userBO){
RequestRegisterHistory requestRegisterHistory = new RequestRegisterHistory();
User user = new User();
// ..
requestRegisterHistoryRepository.save(requestRegisterHistory);
userRepository.save(user);
return user;
}
}
mvc-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="sec://www.springframework.org/schema/mvc"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<context:component-scan base-package="com.myapp.controller" />
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />
<mvc:resources mapping="/resources/**" location="resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
<beans:property name="order" value="1" />
</beans:bean>
<beans:bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<beans:property name="favorPathExtension" value="false" />
<beans:property name="favorParameter" value="true" />
<beans:property name="parameterName" value="mediaType" />
<beans:property name="ignoreAcceptHeader" value="true"/>
<beans:property name="useJaf" value="false"/>
<beans:property name="defaultContentType" value="application/json" />
<beans:property name="mediaTypes">
<beans:map>
<beans:entry key="json" value="application/json" />
<beans:entry key="xml" value="application/xml" />
</beans:map>
</beans:property>
</beans:bean>
<mvc:interceptors>
<beans:bean
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<beans:property name="paramName" value="lang" />
</beans:bean>
<beans:bean class="com.myapp.component.AppInterceptor" />
</mvc:interceptors>
<beans:bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
<beans:property name="supportedMediaTypes" value="image/jpeg" />
</beans:bean>
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<beans:property name="maxUploadSize" value="99999999999" />
</beans:bean>
</beans:beans>
I am using Spring Version : 4.1.4 and MySQL Table : MyISAM
Stacktrace
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:248)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:214)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy37.save(Unknown Source)
at com.myapp.service.AdminUserManagementService.saveUser(AdminUserManagementService.java:460)
at com.myapp.service.AdminUserManagementService$$FastClassBySpringCGLIB$$f21244b7.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
How do I configure so I would require #Transactional annotation and any transaction get rolled back during exceptions ?
The issue was with table engine that's MyISAM. The transaction is able to rollback after I changed the engine to InnoDB.
Setting the hibernate.dialect to org.hibernate.dialect.MySQLInnoDBDialect ensure the creation of table with InnoDBin the future.
I am trying to setup Hibernate Tools in eclipse. The trouble is that it can't find any mapping files.
I have created a console configuration that points to my environment.properties file and hibernate.cfg.xml. The trouble is that there are no mappings in hibernate.cfg.xml.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
</session-factory>
</hibernate-configuration>
it seems that it is using the spring bean sessionFactory in myproject-persistence.xml (below) to find the required mapping files. I can't see anywhere that this file can be added to the the Console Configuration in eclipse.
<?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" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${hibernate.connection.driver_class}" />
<property name="jdbcUrl" value="${hibernate.connection.url}" />
<property name="user" value="${hibernate.connection.username}" />
<property name="password" value="${hibernate.connection.password}" />
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="25" />
<property name="acquireIncrement" value="5" />
<property name="maxIdleTime" value="1800" />
<property name="numHelperThreads" value="5" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
</props>
</property>
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
<property name="mappingLocations">
<list><value>classpath*:com/mybusiness/myproject/platform/api/**/*.hbm.xml</value></list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven />
</beans>
How can I get this working?
UPDATE
I managed to get a single Mapping working by adding it to the 'Mappings' tab in 'Edit Configuration'. However, I can't use wildcards here and would have to add every mapping manually.
Hibernate Tools is not available under Hibernate 4.x version. It is available with version 3.2. If you are using maven, the dependency goes as:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.4.GA</version>
<scope>runtime</scope>
</dependency>
Now, the hibernate configuration for the tools got nothing to do with spring. An example xml will be (values in this example is for sql server):
<?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 name="reversengineeringfactory">
<property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:jtds:sqlserver://myinstance:port/mydb</property>
<property name="hibernate.connection.username">dbuser</property>
<property name="hibernate.connection.password">dbpass</property>
<property name="hibernate.default_catalog">mydb</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
</session-factory>
</hibernate-configuration>
Now, For configuring the hibernate config xml in eclipse, you should choose Hibernate Perspective --> Edit Configuration --> Go for configuration File Setup.
A sample reverse engineering xml is below (gives granular control over code generation)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >
<hibernate-reverse-engineering>
<table-filter match-schema="dbo" match-name="Employee"
package="com.maggu.domain.model" />
<table-filter match-schema="dbo" match-name="Company"
package="com.maggu.domain.model" />
<table schema="dbo" name="Employee">
<primary-key>
<generator class="identity" />
</primary-key>
</table>
<table schema="dbo" name="Company">
<primary-key>
<generator class="identity" />
</primary-key>
</table>
</hibernate-reverse-engineering>
HTH
if you are using annotations to create your persistence entities than you can do like:
<bean id = "mySessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name = "packagesToScan">
<list>
<value>entityclasses</value>
</list>
</property>
where entityclasses is the package which contains all your entity classes. Let me know if it helps!!
I'm trying to create a JSF2 application which uses Spring3 for the DI and hibernate to handle the persistence.
I'm stock on the following error and don't know how to proceed:
26/10/2012 1:57:04 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.InvalidMappingException: Unable to read XML
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:567)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:385)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:284)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1079)
at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:1002)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:506)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1317)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1065)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.hibernate.InvalidMappingException: Unable to read XML
at org.hibernate.internal.util.xml.MappingReader.readMappingDocument(MappingReader.java:109)
at org.hibernate.cfg.Configuration.add(Configuration.java:478)
at org.hibernate.cfg.Configuration.add(Configuration.java:474)
at org.hibernate.cfg.Configuration.add(Configuration.java:647)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:685)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:272)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 36 more
Caused by: org.dom4j.DocumentException: Connection refused: connect Nested exception: Connection refused: connect
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.internal.util.xml.MappingReader.readMappingDocument(MappingReader.java:78)
... 43 more
my applicationContext.xml is listed below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.myapp.techrro" />
<context:annotation-config />
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view">
<bean class="com.myapp.util.ViewScope" />
</entry>
</map>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver">
</property>
<property name="url" value="jdbc:jtds:sqlserver://localhost:1433/myapp">
</property>
<property name="username" value="mydb"></property>
<property name="password" value="somepass"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">20</prop>
<prop key="hibernate.c3p0.idle_test_period">300</prop>
<prop key="hibernate.c3p0.timeout">1800</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
<prop key="c3p0.acquire_increment">1</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/myapp/techrro/hibernate/UserOrderHist.hbm.xml
</value>
<value>com/myapp/techrro/hibernate/UserAccessHist.hbm.xml
</value>
<value>com/myapp/techrro/hibernate/User.hbm.xml</value>
</list>
</property>
</bean>
<bean id="userOrderHistDAO" class="com.myapp.techrro.hibernate.userOrderHistDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="userAccessHistDAO" class="com.myapp.techrro.hibernate.userAccessHistDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="userDAO" class="com.myapp.techrro.hibernate.userDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
</beans>
Update:
below are my mapping files, they were generated by myEclipse:
User.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd ">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.myapp.techrro.hibernate.User" table="User" schema="dbo" catalog="mydb">
<id name="user_PK" type="java.lang.Long">
<column name="user_PK" />
<generator class="identity" />
</id>
<property name="username" type="java.lang.String">
<column name="username" length="20" not-null="true" unique="true" />
</property>
<property name="password" type="java.lang.String">
<column name="password" length="40" not-null="true" />
</property>
<property name="userRole" type="java.lang.String">
<column name="userRole" length="1" not-null="true" />
</property>
<property name="active" type="java.lang.String">
<column name="active" length="1" />
</property>
<property name="type" type="java.lang.String">
<column name="type" length="3" not-null="true" />
</property>
<property name="firstName" type="java.lang.String">
<column name="firstName" length="30" />
</property>
<property name="lastName" type="java.lang.String">
<column name="lastName" length="30" />
</property>
<set name="userOrderHistLog" inverse="true">
<key>
<column name="user_PK" />
</key>
<one-to-many class="com.myapp.techrro.hibernate.userOrderHist" />
</set>
<set name="userAccessHistLog" inverse="true">
<key>
<column name="user_PK" not-null="true" />
</key>
<one-to-many class="com.myapp.techrro.hibernate.userAccessHist" />
</set>
</class>
</hibernate-mapping>
UserOrderHist.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd ">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.myapp.techrro.hibernate.userOrderHist" table="userOrderHist" schema="dbo" catalog="mydb">
<id name="userOrderHis_PK" type="java.lang.Long">
<column name="userOrderHis_PK" />
<generator class="identity" />
</id>
<many-to-one name="user" class="com.myapp.techrro.hibernate.User" fetch="select">
<column name="user_PK" />
</many-to-one>
<property name="action" type="java.lang.String">
<column name="action" length="1" not-null="true" />
</property>
<property name="prod" type="java.lang.String">
<column name="username" length="20" not-null="true" />
</property>
<property name="type" type="java.lang.String">
<column name="userRole" length="1" />
</property>
<property name="Updated" type="java.lang.String">
<column name="deleteFG" length="1" />
</property>
</class>
</hibernate-mapping>
UserAccessHist.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd ">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.myapp.techrro.hibernate.userAccessHist" table="userAccessHist" schema="dbo" catalog="mydb">
<id name="userAccessHistPK" type="java.lang.Long">
<column name="userAccessHistPK" />
<generator class="identity" />
</id>
<many-to-one name="user_PK" class="com.myapp.techrro.hibernate.User" fetch="select">
<column name="adminUserPK" not-null="true" />
</many-to-one>
<property name="createdDate" type="java.sql.Timestamp">
<column name="createdDate" length="23" not-null="true" />
</property>
<property name="accessDetail" type="java.lang.String">
<column name="accessDetail" length="100" not-null="true" />
</property>
</class>
</hibernate-mapping>
Can someone please possible causes of such error? Thanks
Based on your stacktrace (org.hibernate.InvalidMappingException: Unable to read XML), the problem is most likely in one of your hibernate mapping XML files.
Update:
Now that you have posted your hibernate files, it appears that you have an extra space at the end of the DTDs. Removing the trailing spaces should fix the problem.
I'm learning spring hibernate zk stack, and doing my first crud following this tutorial
I put applicationContext.xml into webapp/WEB-INF, and .hbm.xml to resources/mappings
But I dont know why my hbm files keep showing can not find my pojos.
in github https://github.com/kossel/firstzk
I have this structure
applicationContext.xml
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- set other Hibernate properties in hibernate.cfg.xml file -->
<property name="configLocation" value="classpath:/com/iknition/firstzk/hibernate/hibernate.cfg.xml" />
</bean>
hibernate.cfg.xml
<mapping resource="com/iknition/firstzk/hibernate/Company.hbm.xml" />
<mapping resource="com/iknition/firstzk/hibernate/Contact.hbm.xml" />
Company.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.iknition.firstzk.beans">
<class name="Contact" table="contact">
<id name="idcontact" column="idcontact" type="integer">
<generator class="increment" />
</id>
<property name="name" column="name" type="string" />
<property name="email" column="email" type="string" />
<many-to-one name="company" column="companyId" class="com.iknition.firstzk.beans.Company" outer-join="true" />
</class>
</hibernate-mapping>
Contact.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.iknition.firstzk.beans">
<class name="Contact" table="contact">
<id name="idcontact" column="idcontact" type="integer">
<generator class="increment" />
</id>
<property name="name" column="name" type="string" />
<property name="email" column="email" type="string" />
<many-to-one name="company" column="companyId" class="com.iknition.firstzk.beans.Company" outer-join="true" />
</class>
</hibernate-mapping>
UPDATE:
I have reference to contact.hbm.xml too, I missed to put it here.
by "why my hbm files keep showing can not find my pojos" I mean, when I try to build the application, I keep getting error of "Caused by: org.hibernate.MappingException: entity class not found: com.iknition.firstzk.beans.Contact" I have changed many times the location of those configuration files, and still getting same error.
Hmmm... never tried using an external hibernate.cfg.xml. But I think specifying that only loads the properties. You might still need to set the mapping in a separate property.
Here's what my config usually looks like:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<bean
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="propertiesArray">
<list>
<props>...</props>
</list>
</property>
</bean>
</property>
<property name="mappingLocations" value="classpath:com/iknition/firstzk/hibernate/*.hbm.xml"/>
</bean>
I think you have to specify mappingLocations one-by-one like:
<property name="mappingLocations">
<util:list>
<value>hibernate/Company.hbm.xml</value>
<value>hibernate/Contact.hbm.xml</value>
</util:list>
</property>