Hibernate H2 database locks after project rebuild - java

I am setting up a Spring hibernate H2 application. When the server starts everything works but after an update (rebuild project in eclipse without restarting Tomcat) I get the following error messages saying that the database file can't be accessed.
Error Messages:
java.lang.IllegalStateException: The file is locked: nio:/home/bob/dataStore.mv.db [1.4.187/7]
java.nio.channels.OverlappingFileLockException
org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Database may be already in use:
After Googling this error I tried adding File_LOCK=NO and DB_CLOSE_ON_EXIT=TRUE to the URL but no luck.
Context.xml file
<context:annotation-config />
<context:component-scan base-package="com" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<!-- <property name="url" value="jdbc:h2:tcp://localhost/~/dataStore;FILE_LOCK=NO;DB_CLOSE_ON_EXIT=TRUE" /> -->
<property name="url" value="jdbc:h2:file:~/dataStore;FILE_LOCK=NO;DB_CLOSE_ON_EXIT=TRUE;MVCC=TRUE" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.entities" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
<prop key="format_sql">true</prop>
<prop key="use_sql_comments">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
What can I do so that the database does not get locked every time the project is rebuilt.
Also, eclipse is rebuilding the application after everytime the database is updated. How can I stop this?

Try DB_CLOSE_ON_EXIT=FALSE, from the Spring docs
If, for whatever reason, you do configure the connection URL for an embedded database, care should be taken to ensure that the database’s automatic shutdown is disabled. If you’re using H2 you should use DB_CLOSE_ON_EXIT=FALSE to do so.

if need to create multipul connecation then you need to use below code :
<property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/C:\Database\Data\production;"/>

Related

Hibernate Spring MVC Extremely Slow

I'm building manager web project with Spring MVC , Hibernate and MySQL. When i write the code to list all the regency i have in database. It run very fast in couple first times, but when i reload the page repeatedly (8 - 10 times), my page just keep the loading mode and no sign of stopping. First, i use MSSQL Server then i change to MySQL, nothing changed, i turn off the firewall, still not working.
This my dispatcher-servlet.xml:
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" cache- period="31556926"/>
<mvc:annotation-driven />
<context:component-scan base-package="com.hinet.storage" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver"
p:viewClass=" org.springframework.web.servlet.view.tiles3.TilesView"/>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer"
p:definitions="/WEB-INF/tiles/tiles.xml"/>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/database.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.hinet.storage" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="configurationClass">org.hibernate.cfg.AnnotationConfiguration</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
And this is RengencyDAOImpl:
#Repository("regencyDAO")
#Transactional
public class RegencyDAOImpl extends BaseDAOImpl implements RegencyDAO{
#Override
public List<Regency> getRegencies() {
String sql = "from Regency as re where re.isDelete != true";
Query query = this.openSession().createQuery(sql, Regency.class);
List<Regency> regencies = query.list();
return regencies;
}
}
It has given me headache in the past few days! Does anyone know the
reason that cause this problem?
I think you exhaust your datasource (i.e opening without closing connection).
What does openSession() do? I think it should be something like getCurrentSession().
If you open new session, you should close it.

Spring Cfg+Hibernate Cfg and Anotations

I want to make a test with HQL but the mapping tables is with Annotations.
Hibernate configuration file is in the /WEB-INF/spring-config-ws.xml :::>
<!-- Activate transaction declarations with annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Property files application uses -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!-- JNDI DataSource -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="${dataSource.jndiName}" />
<property name="lookupOnStartup" value="false"/>
<property name="cache" value="true"/>
<property name="proxyInterface" value="javax.sql.DataSource"/>
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
<property name="packagesToScan">
<list>
<value>es.sergas.rprof.profesional.domain</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.default_schema">${hibernate.default_schema}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">true</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
</props>
</property>
</bean>
<!-- Transaction manager for Hibernate SessionFactory -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
When I run a list, I get that you do not find the hibernate cfg:
hibernate.cfg.xml not found
I just want to list a mapped class with annotations, but HQL
I feel my level of English is so low. Thank you
Make sure your hibernate.cfg.xml is inside src/main/resources, if the file is not there you need to specify the right location, so put it inside this folder that your problem will be solved.
Note that we don’t have to explicitly mention the mapping or configuration or properties
files, because the Hibernate runtime looks for default filenames, such as hibernate.
cfg.xml or hibernate.properties, in the classpath and loads them. If we have a nondefault
name, make sure you pass that as an argument—like configure("my-hibcfg.
xml"), for example.

Configure hibernate in spring application

I have successfully configured hibernate and I can run transactions but only from the psvm of the DAO class. I want to configure it with my spring app using the same configuration file i.e. hibernate.cfg.xml.
How can I do this? Most tutorials I've read simply neglect the hibernate configuration file.
You can add this code to you xml file to configure hibernate.
<!-- Hibernate Related Configuration. -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://192.168.1.9:5432/dbname"/>
<property name="username" value="postgres"/>
<property name="password" value="pwd"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
The hibernate.cfg.xml file is specified for the LocalEntityManagerFactoryBean, along with your DataSource
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath*:META-INF/hibernate.cfg.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
Here you can find an example of a Spring XML configuration containing some Hibernate configuration

Quartz Cron scheduler in Spring with jdbc store

I need to create Cron service in Spring, but I can not find enough info how to do it with jdbc store. I want Quartz to use my present connection to Datasource, my database is PostgreSql. I need to create use jdbc store, because task should be done even if server was down.
You can try something like this
<bean id="scheduler-JDBC" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" abstract="true">
<property name="dataSource" ref="myDataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="jobFactory">
<bean class="org.springframework.scheduling.quartz.SpringBeanJobFactory" />
</property>
<property name="overwriteExistingJobs" value="true" />
<property name="quartzProperties">
<props>
<prop key="org.quartz.jobStore.isClustered">false</prop>
<prop key="org.quartz.jobStore.driverDelegateClass">org.quartz.impl.jdbcjobstore.StdJDBCDelegate</prop>
<prop key="org.quartz.scheduler.instanceId">AUTO</prop>
<prop key="org.quartz.scheduler.skipUpdateCheck">true</prop>
</props>
</property>
</bean>
<bean id="cronScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" parent="scheduler-JDBC">
<property name="startupDelay" value="10" />
<property name="autoStartup" value="true" />
<property name="applicationContextSchedulerContextKey" value="applicationContext"/>
<property name="triggers">
<list>
<ref bean="myTrigger" />
</list>
</property>
</bean>
Download Quartz distribution from http://quartz-scheduler.org/ and you will find the database script for needed tables in docs/dbTables.

JMS error: can not send into foreign destinations

I use Spring-configured jms template with tibco jms library.
I get jms connection factory and topic with JNDI and these objects are not null. But when I try to send message or add listener I get this exception:
For listener:
Exception in thread "main" org.springframework.jms.InvalidDestinationException: Can not send into foreign destinations; nested exception is javax.jms.InvalidDestinationException: Can not send into foreign destinations
at org.springframework.jms.support.JmsUtils.convertJmsAccessException(JmsUtils.java:277)
at org.springframework.jms.support.JmsAccessor.convertJmsAccessException(JmsAccessor.java:168)
at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:474)
at org.springframework.jms.core.JmsTemplate.receiveSelected(JmsTemplate.java:700)
at org.springframework.jms.core.JmsTemplate.receive(JmsTemplate.java:682)
at org.springframework.jms.core.JmsTemplate.receive(JmsTemplate.java:674)
For sender:
Exception in thread "main" org.springframework.jms.InvalidDestinationException: Invalid or foreigndestination; nested exception is javax.jms.InvalidDestinationException: Invalid or foreigndestination
at org.springframework.jms.support.JmsUtils.convertJmsAccessException(JmsUtils.java:277)
at org.springframework.jms.support.JmsAccessor.convertJmsAccessException(JmsAccessor.java:168)
at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:474)
at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:539)
at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:531)
Client app is working with the same topic without problems (so jms server is running). Do you have any ideas? I read about this exception in javadoc, but can't find how to understand the root issue and fix it.
Thanks
UPD:
JMS-related part of config:
<bean id="JmsFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="${jms.factory}"/>
<property name="proxyInterface" value="javax.jms.TopicConnectionFactory" />
<property name="lookupOnStartup" value="false" />
<property name="jndiEnvironment">
<props>
<prop key="java.naming.provider.url">${jms.namingProvider}</prop>
<prop key="java.naming.factory.initial">${jms.namingFactory}</prop>
<prop key="java.naming.referral">${jms.namingReferral}</prop>
<prop key="java.naming.security.credentials">${jms.securityCredentials}</prop>
<prop key="java.naming.security.principal">${jms.securityPrincipal}</prop>
</props>
</property>
</bean>
<bean id="JmsTopic" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="${jms.topic}"/>
<property name="proxyInterface" value="javax.jms.Topic" />
<property name="lookupOnStartup" value="false" />
<property name="jndiEnvironment">
<props>
<prop key="java.naming.provider.url">${jms.namingProvider}</prop>
<prop key="java.naming.factory.initial">${jms.namingFactory}</prop>
<prop key="java.naming.referral">${jms.namingReferral}</prop>
<prop key="java.naming.security.credentials">${jms.securityCredentials}</prop>
<prop key="java.naming.security.principal">${jms.securityPrincipal}</prop>
</props>
</property>
</bean>
<bean id="UserCredentialsConnectionFactory"
class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
<property name="targetConnectionFactory">
<ref bean="JmsFactory" />
</property>
<property name="username" value="${jms.user}" />
<property name="password" value="${jms.password}" />
</bean>
<bean id="JmsTemplate"
class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory"
ref="UserCredentialsConnectionFactory" />
<property name="defaultDestination">
<ref bean="JmsTopic"/>
</property>
<property name="pubSubDomain" value="true" />
</bean>
It sounds like you have it configured so that it is attempting to create a destination rather than do a jndi lookup to get the destination that has been defined on the EMS instance.
You need to post your spring config to be sure though.
edit: if you set a destinationname on the JmsTemplate and provide it with a JndiDestinationResolver then it should work

Categories