Spring with JPA not persisting objects - spring

I have read many tutorials to config spring with JPA. I am using a local MySQL database and i have this context:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- DataSource Setup -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="vitornobrega" />
<property name="password" value="" />
</bean>
<!-- Entity Manager Factory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.vitornobrega.myapp.entities" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
</beans>
I have a test on JUnit to test my DAO and works nice but when i try to persist an entity with this config, i never the in hibernate log the insert command but in test case i see it. If i try to make a entitymanager.flush i get an exception because any transaction is running.
What i should change to can make persist on my local database with this entities?
thanks

If i try to make a entitymanager.flush i get an exception because any transaction is running.
If I'm reading that right, the problem is you're trying to save something without starting a transaction. Transactions are required when changing persistent state.

In order to be able to persist in database it is mandatory to be within a transaction. So the better you can solve it is to annotate #Transactional ... e.g. on the method
This also make me crazy for couple of hours some time ago.

are you using annotations in your classes? if so please make sure you
<context:component-scan base-package="com.vitornobrega.myapp"> because arpart from the jpa configurations i can see where you are injecting your dependencies.

Related

moving from oracle sql to couchBase db just by changing connection

I have a spring mvc application that works on oracle server, I am currently using the spring JPA to store and retrieve data. can i move from oracle sql to couchbase server just by changing the data source, If so how do I configure my datasource to work with couchbase
The bean definition is as follows
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx/ http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:component-scan base-package="org.test.project"></context:component-scan>
<context:property-placeholder location="classpath:application.properties" ></context:property-placeholder>
<jpa:repositories base-package="org.test.project"
entity-manager-factory-ref="entityManagerFactoryBean"></jpa:repositories>
<bean id="dbClassImpl" class="org.test.project.DbClassImpl" />
<!--EntityManagerFactory -->
<bean id="entityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="org.test.project" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" >
<property name="showSql" value="true"/>
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="someurl" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<tx:annotation-driven proxy-target-class="true" />
Here is the official documentation about it https://docs.spring.io/spring-data/couchbase/docs/current/reference/html/#configuration-xml
However, you will need to change a few extra things to make it work:
1 - One of the main advantages of Document Databases is to avoid unnecessary joins. If you simply transition from relational to Document without changing your model, you won't get the most of it. (https://blog.couchbase.com/json-data-modeling-rdbms-users/)
2 - Couchbase don't support LocaDateTime/ZonnedDateTime yet, you will need to write a converter.
3 - Your repositories should have a few extra annotations
(https://blog.couchbase.com/couchbase-spring-boot-spring-data/)
4 - If you are using JPQL, you will need to slightly modify it to use the N1QL syntax (https://docs.spring.io/spring-data/couchbase/docs/current/reference/html/#couchbase.repository.n1ql)

Getting random "Connection is read-only" - Spring

I've spent the last couple of days debugging some really strange errors.
I have an exposed WebService which calls a service-metod called "addNewOrder"
This service-method is annotated with
#Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
This service-method will need to read and write to the database.
I would think that the annotation above would ensure that every time this method is called, i'm getting a new transaction that can do what is needed.
But about 50% of the time, when "addNewOrder" is called, i get these strange errors:
org.hibernate.engine.jdbc.spi.SqlExceptionHelper:143 - SQL Error: 0, SQLState: S1009
org.hibernate.engine.jdbc.spi.SqlExceptionHelper:144 - Connection is read-only. Queries leading to data modification are not allowed
Does anyone have any clue as to why this might happen? And why is it random?
Im using Spring 3.2.4, Hibernate 4.1.7, Mysql-connector 5.1.26
This is my applicationContext snippet:
<?xml version="1.0" encoding="iso-8859-1"?>
<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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="no.aida.model"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${jpa.show.sql}"/>
<property name="generateDdl" value="${jpa.generate.ddl}"/>
<property name="databasePlatform" value="${jpa.dialect}"/>
</bean>
</property>
<property name="jpaDialect">
<bean id="jpaDialect" class="no.aida.dao.hibernate.IsolationSupportHibernateJpaDialect" />
</property>
</bean>
<!-- javax.sql.DataSource supplied by Jakarta Commons Connection Pooling -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${mysql.db.driver}"/>
<property name="url" value="${mysql.db.url}"/>
<property name="username" value="${mysql.db.username}"/>
<property name="password" value="${mysql.db.password}"/>
<property name="initialSize" value="3" />
<property name="maxActive" value="30" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- Enable #Transactional support -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
Well i'll be damned. Just a few mins after posting this i finally found the error. The reason it is random is because I have another service-method called "getStatus" which is annotated by read-only. And if this is called then every request using the same connection will also be read-only. But i still cant understand why the read-only is not re-set when the connection is used on a method annotated with readOnly = false...
And to add to the saga. The reason why the connections was not reset, was because we had implemented a custom JpaDialect that had forgotten to reset the connections... doooooh!
value="${mysql.db.url}"
Could you please specify the connect url? Do you use:
failOverReadOnly=false
or not? This should help.
BR, Ilya

Change hibernate.connection.url from within Spring

I am using Hibernate in combination with Spring. As database I am currently using HSQL, which stores its data in a file (like SQLite). The path to the HSQL file is currently hard-coded in the persistence.xml. How can I access and change this value at runtime, so a user can load and save from/to an arbitrary HSQL file?
persistence.xml:
<persistence 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_1_0.xsd"
version="1.0">
<persistence-unit name="something-unit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" />
<property name="hibernate.connection.url" value="jdbc:hsqldb:file:~/something-db/somethingdb" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
Spring 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:context="http://www.springframework.org/schema/context"
xmlns:data="http://www.springframework.org/schema/data/jpa"
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/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Database Setup -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="something-unit" />
</bean>
<data:repositories base-package="com.something.playlist"/>
<!-- Transaction Setup -->
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
</beans>
Thanks for any hint!
You can specify a JNDI datasource and pass it to Hibernate. Or you can define your own plugin strategy for obtaining JDBC connections by implementing the interface org.hibernate.connection.ConnectionProvider
For more hints see: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html
Edit 2/16: There is an example on StackOverflow on creating a custom ConnectionProvider: How can I set Datasource when I'm creating Hibernate SessionFactory?
If you are going to change the data source on the fly, rather than at the startup, you will have to restart the Hibernate session factory. To do it correctly, you will have to make sure that no transactions are running in it at the time of the restart. Following question/answers would help you with that: Hibernate Sessionfactory restart | Spring
A commonly used strategy is to define all runtime configurations in one or several *.properties files and use spring's PropertyPlaceholderConfigurer to load the values and substitute the placeholder in applicationContext.xml, read more here: Best ways to deal with properties values in XML file in Spring, Maven and Eclipses.
app.properties:
# Dadabase connection settings:
hibernate.connection.driver_class=org.hsqldb.jdbcDriver
hibernate.connection.url=jdbc:hsqldb:file:~/something-db/somethingdb
hibernate.connection.username=sa
hibernate.connection.password=changeit
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hbm2ddl.auto=update
... ...
applicationContext-dataStore.xml:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<!-- Default location inside war file -->
<value>classpath:app.properties</value>
<!-- Environment specific location, a fixed path on deployment server -->
<value>file:///opt/my-app/conf/app.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
... ...
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${hibernate.connection.driver_class}" />
<property name="url" value="${hibernate.connection.url}" />
<property name="username" value="${hibernate.connection.username}" />
<property name="password" value="${hibernate.connection.password}" />
</bean>
One problem here is the PropertyPlaceholderConfigurer doesn't parse persistence.xml, the solution is to move all hibernate configuration into Spring's applicationContext.xml, as it is not necessary to set them in persistence.xml. read more here: loading .properties in spring-context.xml and persistence.xml.
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL"/>
</persistence>
applicationContext-datSource.xml:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${hibernate.connection.driver_class}"/>
<property name="url" value="${hibernate.connection.url}"/>
<property name="username" value="${hibernate.connection.username}"/>
<property name="password" value="${hibernate.connection.password}"/>
</bean>
... ...
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:./META-INF/persistence.xml"/>
<property name="persistenceUnitName" value="JPAService"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="${hibernate.dialect}"/>
<property name="showSql" value="true" />
<property name="generateDdl" value="true"/>
</bean>
</property>
<property name="jpaProperties">
<!-- set extra properties here, e.g. for Hibernate: -->
<props>
<prop key="hibernate.hbm2ddl.auto">${hbm2ddl.auto}</prop>
</props>
</property>
</bean>
Note that the web application need to be restarted every time you alter the configuration in /opt/my-app/conf/app.properties, in order to make changes take effect.
Hope this helps.
If you wish to use hibernate via the JPA Abstraction you can we-write your code or service to use an javax.persistence.EntityManagerFactory. Autowire one of these and call createEntityManager(Map map); You can provide a datasource in the map. You could wrap the entity manager with your own implementation that pulls the parameter off a thread-local for creating the datasource.
EDIT: Mis-read the context and saw you are using an EntityManagerFactory. In which case just read the last part where you wrap the Factory with a delegate that creates the correct datasource from a threadlocal.

Spring Quartz simple trigger not firing as expected

I am having a simple trigger bean which should be fired for every 20min.
For that I am specifying the repeatinterval value in properties file. But my job is getting waked up every minute instead of every 20min.
sample xml
<bean id="propertyLoaderJob"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="propertyloader" />
<property name="targetMethod" value="propFlagValidator" />
<property name="concurrent" value="false" />
</bean>
<bean id="propertyLoaderTrigger"
class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="propertyLoaderJob" />
<property name="repeatInterval" value="${quartz.scheduler.repeatInterval}" />
<property name="startDelay" value="${quartz.scheduler.startDelay}" />
</bean>
in the properties file I have these fields
quartz.scheduler.repeatInterval=1200000
quartz.scheduler.startDelay=1000
What could be the possbile reason for this?
Please help.
Thanks in advance.
Have you specified a property placeholder for this,
Using Context namespace,
<?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: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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
. . .
<context:property-placeholder location="quartz.scheduler.properties" />
. . .
</beans>
or Adding PropertyPlaceholderConfigurer bean in application context
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:quartz.scheduler.properties</value>
</property>
</bean>
Are you sure that you are not using any other trigger for the same class/job i.e. propertyLoaderJob. It may have happened that you are using a cron expression as well associated with the same job. It will be great if you can share the complete spring xml file.
For future reference i am answering.
Along with the mentioned part in my question i forgot to add the below code. That is for actually triggering it:
<bean name="nonclusterMode" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="propertyLoaderTrigger" />
</list>
</property>
</bean>
Now it is working as expected.

Spring batch trying to create persistant Batch Job Respository again

This seems to be a stupid issue. I am trying to configure an Oracle10g database for Spring Batch Job Repository (Spring Batch 2.1.7), I was able to have the tables created using the script available at org/springframework/batch/core/schema-oracle10g.sql in core. I also set the property batch.data.source.init to false.
On a clean database my batch program runs fine, successfully creating all the Batch tables/Sequences and populating them with the details of the batch results. However, when I run it again Spring Batch tries to create these tables again and throws "ORA-00955: name is already used by an existing object" exception. What am I doing wrong?
# For Oracle
batch.jdbc.driver=oracle.jdbc.driver.OracleDriver
batch.jdbc.url=jdbc:oracle:thin:#localhost:1521:orcl
batch.jdbc.user=****
batch.jdbc.password=****
batch.schema=****
batch.schema.script=classpath:/org/springframework/batch/core/schema-oracle10g.sql
batch.drop.script=classpath:/org/springframework/batch/core/schema-drop-oracle10g.sql
batch.jdbc.testWhileIdle=true
batch.data.source.init=false
Following is my context file:
<?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:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
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">
<context:property-placeholder location="classpath:batch.properties" />
<context:component-scan base-package="com.myco.mypack" />
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="${batch.schema.script}" />
</jdbc:initialize-database>
<import resource="classpath:/META-INF/spring/module-context.xml" />
<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" lazy-init="true">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager"/>
<property name="databaseType" value="oracle" />
<property name="tablePrefix" value="BATCH_"/>
<property name="isolationLevelForCreate" value="ISOLATION_DEFAULT"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${batch.jdbc.driver}" />
<property name="url" value="${batch.jdbc.url}" />
<property name="username" value="${batch.jdbc.user}" />
<property name="password" value="${batch.jdbc.password}" />
</bean>
</beans>
i do not see the use of batch.data.source.init like this:
<jdbc:initialize-database data-source="dataSource"
enabled="${batch.data.source.init}">
<jdbc:script location="${batch.schema.script}" />
</jdbc:initialize-database>
It's been a while but i think for people searching for this problem it will help to know that you can disable creating the databases by using
spring.batch.initializer.enabled=false
in application.properties as given in the documentation:
http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html
<jdbc:initialize-database data-source="dataSource"
enabled="${batch.data.source.init}">
<jdbc:script location="${batch.schema.script}" />
If I pass Command Line argument -Dbatch.data.source.init=false ,then the intialization is not enabled.
But If I use the below configuration and set enabled to false in the context xml , then initialisation is triggered even though enabled flag is false
<jdbc:initialize-database data-source="dataSource"
enabled="false">
<jdbc:script location="false" />

Resources