Spring + JPA in standalone application doesn't save data in database - spring

I am using
Spring 3.1.1
JPA 2
H2
Hibernate
in standalone Java application. When I run the application, the transaction is executed and when I query the data, the data is retrieved. But the data is not saved when the application is closed.
Please help me.
Here is spring configuration,
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" />
</bean>
<bean id="sharedEntityManager"
class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="1.0">
<persistence-unit name="sling">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.sling.data.Trend</class>
<class>com.sling.data.Gc</class>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:sling;DB_CLOSE_DELAY=-1" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
</properties>
</persistence-unit>
</persistence>
DAO class,
#Repository
public class GcDao {
#PersistenceContext
private EntityManager em;
public GcDao() {
}
#Transactional
public void add(Gc gc){
em.persist(gc);
}
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
public List<Gc> getGc(){
String queryText = " from Gc";
Query query = em.createQuery(queryText);
return query.getResultList();
}
}

I believe you still need to add context:component-scan on your dao package before your tx:anotation-driven element.
<context:component-scan base-package="com.sling.dao" />
<tx:annotation-driven />

Related

An AnnotationConfiguration instance is required to use <myClass>

Below is the EmployeeDaoImpl file which is injecting sessionFactory.
#Repository
public class EmployeeDaoImpl implements EmployeeDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void addEmployee(TestEmployee employee) {
this.sessionFactory.getCurrentSession().save(employee);
}
#SuppressWarnings("unchecked")
#Override
public List<TestEmployee> getAllEmployees() {
return this.sessionFactory.getCurrentSession().createQuery("from TestEmployee").list();
}
#Override
public void deleteEmployee(Integer employeeId) {
TestEmployee employee = (TestEmployee) sessionFactory.getCurrentSession().load(
TestEmployee.class, employeeId);
if (null != employee) {
this.sessionFactory.getCurrentSession().delete(employee);
}
}
}
Below is my employee-servlet 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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<context:component-scan base-package="com.rights.controller" />
<mvc:annotation-driven />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="employeeDAO" class="com.rights.dao.EmployeeDaoImpl"></bean>
<bean id="employeeManager" class="com.rights.services.EmployeeManagerImpl"></bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
I am getting An AnnotationConfiguration instance is required error. I have searched it on net but not able to solve this. I have the run configuration. I am using hibernate 3 and spring 3.1 JARS. Kindly help
daoin
<context:component-scan base-package="com.rights.controller" />
you seems like you forgot the package of your repository you should add it using :
<context:component-scan base-package="com.rights.controller com.rights.dao" />
in the configuration you posted, the class with annotation #Repository may not be post-processed by spring, if it package is not include in the component scan
I hope it may help you

hibernate.hbm2ddl.import_files in persistence.xml is not working

I need that hibernate read a sql file before start junit tests, so I did the following configuration in persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.connection.url" value="jdbc:hsqldb:hsql://localhost:9001/test" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.id.new_generator_mappings" value="true" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.hbm2ddl.import_files" value="/META-INF/load.sql" />
</properties>
</persistence-unit>
</persistence>
The applicationContext.xml to load spring context:
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.test" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="test" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"></bean>
</beans>
Junit tests extends the class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:/applicationContext.xml" })
#TestExecutionListeners(inheritListeners = false, listeners = {
TransactionalTestExecutionListener.class, DependencyInjectionTestExecutionListener.class })
#TransactionConfiguration(defaultRollback = true)
#Transactional
public abstract class UnitTestConfiguration {}
When I run the junit tests, the file load.sql is not been imported and no errors are shown.
I'm using Hibernate 4 and Spring 3.0.5.
I solved my problem by putting the load.sql in src/test/resource/ folder.
This way isn't necessary to specify in persistence.xml where the sql file is.
I think(I usually use it) you should include it in your applicationContext.xml:
<import resource="classpath:/path_to_persistence/persistence.xml" />
Also you can specify several configuration files in test #ContextConfiguration:
#ContextConfiguration(locations = { "classpath:/applicationContext1.xml", ... ,"classpath:/applicationContextn.xml" })
Just put a file with name import.sql on src/test/resources directory.
The default value of property javax.persistence.hibernate.hbm2ddl.import_files is
import.sql.
Check: http://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html

datasource vs. persistence.xml for database config parameter

In my project I'm using spring with jpa, and when I arrive to the config files, I mean appContext.xml and persistence.xml, I have encoutered the following situation : when I put the db config in the persistence.xml and I remove the datasource from the appContext.xml nothing works but when I move the bd config to the appContext into the dataSource tag (with properties) the app is running, can anyone explain this? thanks in advance!
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="test" transaction-type="RESOURCE_LOCAL">
<class>ma.persistence.dto.Subscriber</class>
<class>ma.persistence.dto.Profile</class>
<class>ma.dto.Title</class>
</persistence-unit>
</persistence>
AppContext.xml :
<?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">
<context:component-scan base-package="ma.persistence"/>
<context:annotation-config />
<tx:annotation-driven />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/MyDB"
p:username="username" p:password="password" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform"
value="org.hibernate.dialect.MySQLInnoDBDialect" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="MYSQL" p:showSql="true" />

unit testing spring/jpa/hibernate and google-appengine with cloud SQL : API package rdbms missing

I try to make a simple test with spring/jpa/hibernate and GAE/Google Cloud SQL.
But I can't find the right configuration and I always keep getting :
Caused by: com.google.apphosting.api.ApiProxy$CallNotFoundException: The API package 'rdbms' or call 'OpenConnection()' was not found.
at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:98) ~[appengine-api-1.0-sdk-1.6.4.1.jar:na]
at com.google.appengine.api.rdbms.RdbmsApiProxyClient$ApiProxyBlockingInterface.makeSyncCall(RdbmsApiProxyClient.java:95) ~[appengine-api-1.0-sdk-1.6.4.1.jar:na]
at com.google.appengine.api.rdbms.RdbmsApiProxyClient$ApiProxyBlockingInterface.openConnection(RdbmsApiProxyClient.java:73) ~[appengine-api-1.0-sdk-1.6.4.1.jar:na]
at com.google.cloud.sql.jdbc.internal.SqlProtoClient.openConnection(SqlProtoClient.java:58) ~[appengine-api-1.0-sdk-1.6.4.1.jar:na]
at com.google.cloud.sql.jdbc.Driver.connect(Driver.java:66) ~[appengine-api-1.0-sdk-1.6.4.1.jar:na]
at com.google.cloud.sql.jdbc.Driver.connect(Driver.java:26) ~[appengine-api-1.0-sdk-1.6.4.1.jar:na]
at java.sql.DriverManager.getConnection(DriverManager.java:579) ~[na:1.7.0]
at java.sql.DriverManager.getConnection(DriverManager.java:190) ~[na:1.7.0]
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:192) ~[hibernate-core-4.1.2.Final.jar:4.1.2.Final]
versions :
Spring framework : 3.1.1
Hibernate : 4.1.2
Google App Engine : 1.6.4.1
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_2_0.xsd"
version="2.0">
<persistence-unit name="gae-test" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.gro.gae.domainmodel.user.UserEntity</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"></property>
<property name="hibernate.show_sql" value="true"></property>
<property name="hibernate.hbm2ddl.auto" value="update"></property>
<property name="hibernate.connection.url" value="jdbc:google:rdbms://sqlpetstocks:petstocks/dngdatabase"></property>
<property name="hibernate.connection.driver_class" value="com.google.appengine.api.rdbms.AppEngineDriver"></property>
<property name="hibernate.connection.driver_class" value="com.google.cloud.sql.Driver"></property>
</properties>
</persistence-unit>
</persistence>
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:context="http://www.springframework.org/schema/context" 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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<jpa:repositories base-package="com.gro.gae.persistence"
factory-class="com.gro.gae.persistence.CustomJpaRepositoryFactoryBean" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="gae-test" />
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<context:annotation-config />
<tx:annotation-driven />
</beans>
unit test :
#RunWith(org.springframework.test.context.junit4.SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:applicationContext-persistence.xml" })
#TestExecutionListeners( { DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class })
#TransactionConfiguration(defaultRollback = true)
#Transactional
public class ConfigurationTest {
#Test
public void testConfig(){
}
}
Any ideas ?
Thanks
Guillaume
Too late but maybe it'll help someone.
I found the same problem and the VM args didn't work under JUnit execution.
The solution was for me to define another entityManager/persistenceUnit for tests.
The key was to change in the new testPersistence.xml the properties:
<property name="javax.persistence.jdbc.driver" value="com.google.appengine.api.rdbms.AppEngineDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:google:rdbms:localhost:3306/DB_NAME" />
with
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/DB_NAME" />
Hope this helps.

Spring jpa transaction business to Dao

business layer:
public class ServiceImpl implements Service{
#Transactional(readOnly = false)
public void createOrUpdateAppPing(String s) {
servicePingDao.createOrUpdateAppPing(s);
}
}
Dao layer
public void createOrUpdateAppPing(String sc) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
pingScService(sc,entityManager);
if(ifHasPingScConfig(sc,entityManager)) {
updateScConfig(sc,entityManager);
} else {
createScConfig(sc,entityManager); }
entityManager.close();
}
here :
** pingScService has select query
** updateScConfig - update query
** createScConfig-insert
config service-datasorce.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:osgi="http://www.springframework.org/schema/osgi"
xmlns:osgix="http://www.springframework.org/schema/osgi-compendium"
xmlns:ctx="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/osgi
http://www.springframework.org/schema/osgi/spring-osgi.xsd
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.xsd
http://www.springframework.org/schema/osgi-compendium
http://www.springframework.org/schema/osgi-compendium/spring-osgi-compendium.xsd
">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="smx4" />
<property name="jpaVendorAdapter" ref="jpaAdapter" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="com.luthresearch.savvyconnect.model.PostgreSQLDialectUuid" />
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${database.driver.class}" />
<property name="url" value="${database.savvyconnect.url}" />
<property name="username" value="${database.savvyconnect.username}" />
<property name="password" value="${database.savvyconnect.password}" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
IN service.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:osgi="http://www.springframework.org/schema/osgi"
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/osgi
http://www.springframework.org/schema/osgi/spring-osgi.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="service"
class="com.services.impl.SServicempl" autowire="byName">
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
Now i want to add transaction support at service layer ...How i can do this.
I tried adding #Transaction annotation but I am getting
javax.persistence.TransactionRequiredException: Executing an update/delete query

Resources