I've got a question to Spring, hibernate and testng.
I am developing an app and try to write a transactional unit test. The question is how could I rollback my database operation when my buissnes method is marked as "transactional"?
The code:
#Test
#ContextConfiguration(locations = { "classpath:applicationContext.xml" })
#TransactionConfiguration(defaultRollback = true)
public class SampleTest extends
AbstractTransactionalTestNGSpringContextTests {
#Autowired
private AuthorDao authorDao;
#BeforeTest
void createAppCtx() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"/applicationContext.xml");
}
#Test
void testStg() {
Person person = new Author();
person.setFirstName("Edward");
person.setLastName("Kowalski");
authorDao.createAuthor(person);
}
In my authorDao I've following method:
#Repository
#Transactional
public class AuthorDao {
#PersistenceContext
private EntityManager entityManager;
public AuthorDao() {
}
public AuthorDao(EntityManager entityManager) {
this.entityManager = entityManager;
}
public Author createAuthor(Person author) {
entityManager.persist(author);
return (Author) author;
}
}
If the application context is needed, I can also attach it.
So as you can see the buisness method is transactional so there is a commit after calling. So point is how to avoid commit in the test class?
Is it possible?
Many thanks for help.
EDIT:
applicationContext:
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.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-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:component-scan base-package="pl.hs" />
<mvc:annotation-driven />
<tx:annotation-driven transaction-manager="myTxManager" />
<beans>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="jdbcPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:project.properties" />
<bean id="myDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${hibernate.connection.driver_class}"
p:url="${hibernate.connection.url}"
p:username="${hibernate.connection.username}"
p:password="${hibernate.connection.password}" />
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="defaultDataSource" ref="myDataSource" />
</bean>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="persistenceUnitName" value="pl.hs" />
</bean>
<bean id="myTxManager" name="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf" />
<!-- <property name="dataSource" ref="myDataSource" /> -->
</bean>
</beans>
</beans>
Persistnce.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
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">
<persistence-unit name="pl.hs"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class> myJavaClasses </class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect"></property>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="create"></property>
</properties>
</persistence-unit>
Add #Transactional to the test method too so that the TransactionConfiguration applies.
The TransactionConfiguration starts a new transaction when the test starts and it rolls it back at the end of the test.
So you don't have to do anything special to roll the current transaction.
If you wanted to add another logic unit after:
authorDao.createAuthor(person);
then you'd better write another test method.
Each test should verify one and only one behavioural unit. If you have several responsibilities tested in a single test method, then you should break those into several tests.
Related
I'm trying to test an application which uses SpringMVC and Hibernate with MySQL. I tried using HSQLDB but since the syntax is not the same as MySQL the queries may not work, so I decided to go to H2.
The problem is that when I run it it says "Table MAILCONFIG not found", and if I created on the INIT syntax it says that already exists.
I have configured a simple test that doesn't do anything, I only want it to run.
I have the following files:
ServiceTest.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"file:src/test/resources/applicationContext.xml"})
#Transactional
#WebAppConfiguration
public class ServiceTest {
private static DataSource ds;
#BeforeClass
public static void setUpConnection(){
ds = new DataSource();
ds.setDriverClassName("org.h2.Driver");
ds.setUrl("jdbc:h2:mem:testDB");
ds.setUsername("sa");
ds.setPassword("");
HibernateConfiguration.dataSourceTest(ds);
}
#AfterClass
public static void cleanConnection(){
HibernateConfiguration.dataSourceTest(null);
}
}
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
<property name="persistenceUnitName" value="testingSetup" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
</bean>
<context:component-scan base-package="com.adistec" />
<context:annotation-config/>
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="testingSetup" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:mem:testDB;DB_CLOSE_DELAY=-1;MODE=MySQL" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.archive.autodetection" value="class, hbm"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
</properties>
</persistence-unit>
MailConfig.java
#Entity
public class MailConfig {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
#Column
String host;
}
I specify the Hibernate configuration in the test because the application uses java classes and not the XML files.
Can anyone help me with this? Or if there is an easier way to test it with java classes is welcome too, I couldn't find out a solution yet.
I want it to work locally and then it has to work with jenkins too, so it can create things that can't do on the VM.
Thank you!
Seems #Table annotation is missing in your MailConfig class.
You can find full working example using spring, hibernate and h2 database from http://mycuteblog.com/h2-database-example-hibernate-spring-boot/
Add #EntityScan(basepackage="com.entity") Annotation in main class
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.test.dao.CustomerDaoImpl</class>
<class>com.test.data.Customer</class>
<class>com.test.dto.CustomerDto</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
</properties>
</persistence-unit>
Class where I am using it:
public class CustomerDaoImpl implements CustomerDao {
#PersistenceContext(unitName = "persistenceUnit")
private EntityManager entityManager;
#Transactional
public List<CustomerDto> getCustomers() {
List<CustomerDto> customers = null;
List<Customer> cust = new ArrayList<Customer>();
Query q = entityManager.createQuery(
"SELECT c"
+ " FROM Customer c ");
EDIT ADDING SPRING-SERVLET.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<context:spring-configured />
<context:component-scan base-package="com.test"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/testdb" />
<property name="username" value="root" />
<property name="password" value="password" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="true" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="1800000" />
<property name="numTestsPerEvictionRun" value="3" />
<property name="minEvictableIdleTimeMillis" value="1800000" />
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/js/" />
<property name="suffix" value=".js" />
</bean>
After I tested this I recognized that Netbeans is giving me error in the class CustomerDaoImpl and it is saying that: "Class is listed in the persistence.xml but it is not annotated". What is correct annotation in this case?
I can see from log that there is correct entitymanager for pu: Closing JPA EntityManagerFactory for persistence unit 'persistenceUnit' and I am creating the dao like that:
#Autowired
CustomerDao customerDao;
When using #autowired annotation, customerDao is null, so I tried to create dao with
customerDao = new CustomerDaoImpl();
and then entitymanager is NULL.
In the persistence.xml you don't need
<class>com.test.dao.CustomerDaoImpl</class>
<class>com.test.dto.CustomerDto</class>
use only
<class>com.test.data.Customer</class>
I am using Spring 3.2 mvc and Hibernate 4 in my project.
hibernate.cfg.xml
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="show_sql">true</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.validator.apply_to_ddl">false</property>
<property name="hibernate.validator.autoregister_listeners">false</property>
servlet-context.xml
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<security:global-method-security pre-post-annotations="enabled"/>
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.abc" />
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
</beans:beans>
DaoImpl Class:
public void add(Entity entity) {
try {
this.sessionFactory.getCurrentSession().save(entity);
this.sessionFactory.getCurrentSession().flush();
} catch (Exception e) {
logger.error("Exception occured " + e);
}
}
This is my project configuration and dao impl class file.
root-context.xml
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="com.abc" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- <property name = "dataSource" ref = "dataSource"></property> -->
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="entityInterceptor" ref ="auditLogInterceptor"/>
</bean>
Issue
As of now in hibernate.cfg.xml, I have mentioned hibernate.connection.autocommit = true and in daoimpl while saving entity I need to call flush after .save .
If I remove hibernate.connection.autocommit = true and .flush from daoimpl class, I observed that .save method in daoimpl is not working, means my data is not inserting and even I cannot see insert query executed by hibernate on console.
hibernate.connection.autocommit = true should not be there in hibernate cfg xml as if I doing operation on multiple table in same transaction and if some error occurred then rollback will not happen.
I want that .save in daoimpl should work even I don't write hibernate.connection.autocommit = true in hibernate cfg xml and .flush.
I am using #Transactional annotation for transaction.
You haven't added any TransactionManager to your configuration:
Remove the following properties:
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
Add a connection pooling DataSource (DBCP2 is a much better alternative than C3P0)
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="your-oracle-driver-url"/>
<property name="username" value="your-username"/>
<property name="password" value="your-password"/>
</bean>
Now add the Sessionfactory Spring proxy:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
Add the TransactionManager bean
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Update
If you have the transaction manager set in a separate spring application context (e.g. root-context.xml), then move these lines from your web context to where the back-end context:
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="com.abc.service" />
<context:component-scan base-package="com.abc.dao" />
And only allow the web context to scan its own beans:
<context:component-scan base-package="com.abc.web" />
It's not good to mix the web and the back-end contexts responsibilities.
My problem solved, I just wrote the annotation #Transactional in the
#Repository
#Transactional
public class AbstractHibernateDao<T extends Serializable> {
private Class<T> clazz;
#Autowired
private SessionFactory sessionFactory;
And that solved that I couldnt Delete or Save without using Flush.
I'm unable to persist data in my Spring/JPA/Tomcat application by calling my userService but when I call it from my unit test the data gets written to the database. Nor is there any exception thrown when calling the service from my controller.
Controller class:
#Controller
#RequestMapping("/")
public class AccessManagementController {
#Autowired
private UserService userService;
#Autowired
private ApplicationProperties applicationProperties;
#RequestMapping(method = RequestMethod.GET, value = "/register")
:
:
:
userService.createNewUser(username, password);
model.addAttribute("loginMessage", "Registration successful; you can now login");
return "/access";
}
}
Working unit test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {
"classpath:/spring/applicationContext.xml",
"classpath:/spring/securityContext.xml",
"classpath:/spring/jpaContext.xml"
})
public class UserServiceTest {
#Autowired
private UserService userService;
#Test
public void userServiceSaveUserTest() {
String testUsername = (new Date()).toString();
userService.createNewUser(testUsername, "password");
User findUser = userService.findByUsername(testUsername);
Assert.assertNotNull(findUser);
Assert.assertEquals(findUser.getUsername(), testUsername);
}
}
applicationContext.xml:
<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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.bytediary"/>
<bean id="applicationProperties" class="com.bytediary.util.ApplicationProperties">
<property name="location" value="classpath:application.properties"/>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="org.springframework.orm.hibernate4.HibernateExceptionTranslator"/>
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
</beans>
jpaContext.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-3.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<context:annotation-config />
<context:component-scan base-package="com.bytediary.entity" />
<jpa:repositories base-package="com.bytediary.repository"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="default"/>
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.bytediary.entity" />
<property name="persistenceXmlLocation" value="classpath:/jpa/persistence.xml" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="database" value="MYSQL" />
<property name="generateDdl" value="true" />
</bean>
</property>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />
</beans>
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="default" transaction-type="RESOURCE_LOCAL">
<class>com.bytediary.entity.User</class>
</persistence-unit>
</persistence>
1 . You do not need
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
Explanation here:
http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.html
Note: A default PersistenceAnnotationBeanPostProcessor will be
registered by the "context:annotation-config" and
"context:component-scan" XML tags. Remove or turn off the default
annotation configuration there if you intend to specify a custom
PersistenceAnnotationBeanPostProcessor bean definition.
2 . Try adding #Transactional to UserService.createNewUser().
i have the following problem. I use Spring and JPA (Hibernate) to persist Data in a Database. But i have an Error during saving the Data. My Database keeps empty after I create a new User. Here are the important files:
UserDao Interface:
import java.util.List;
public interface UserDao {
public User findById(Integer id);
public List<User> findAll();
public User findByEmail(String email);
public void save(User user);
}
UserDaoImpl:
#Repository
public class UserDaoImpl implements UserDao {
#PersistenceContext
private EntityManager em;
#Override
public User findById(Integer id) {
return em.find(User.class, id);
}
#SuppressWarnings("unchecked")
#Override
public List<User> findAll() {
return (List<User>)em.createQuery("from User u").getResultList();
}
#Override
public User findByEmail(String email) {
User user = null;
try
{
user = (User)em.createQuery("from User u where u.email = ?1").setParameter(1, email).getSingleResult();
}
catch(NoResultException e){}
return user;
}
#Override
#Transactional
public void save(User user) {
em.persist(user);
}
}
Context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" 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-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 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd" default-autowire="byName">
<context:component-scan base-package="de.bht.swp.lao.ocp" />
<context:annotation-config />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="username" value="root" />
<property name="password" value="root" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/ocp" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="ocpPU" />
<property name="dataSource" ref="dataSource"/>
<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.MySQL5InnoDBDialect" />
</bean>
</property>
<property name="loadTimeWeaver" ref="loadTimeWeaver"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" >
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<context:load-time-weaver weaver- class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</beans>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" 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">
<persistence-unit name="ocpPU">
</persistence-unit>
When i create a new User i get the following Errorlog:
14:42:05,703 DEBUG [org.hibernate.event.def.AbstractSaveEventListener] - delaying identity-insert due to no transaction in progress
14:42:05,704 DEBUG [org.springframework.orm.jpa.EntityManagerFactoryUtils] - Closing JPA EntityManager
14:42:05,707 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Rendering view [org.springframework.web.servlet.view.RedirectView: unnamed; URL [/user/login.htm]] in DispatcherServlet with name 'dispatcher'
14:42:05,708 DEBUG [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request
I think its a Trancation Error.
I´v already spent so much time in other channels. What means "delaying identity-insert due to no transaction in progress"?
thanks for the help beforehand
greeting
The problem is the #Repository in UserDaoImpl, remove it and make a bean
<bean id="userDao" class="de.bht.swp.lao.ocp.user.UserDaoImpl" />
in your Context.xml
I can't explain this behavior but this is the reason.