springboot hibernate exception entity is not mapped - java

I am trying to unit test my service classes in a spring-hibernate application.
public class UserServiceTest extends SpringAwareTest {
#Autowired
#Qualifier("userService")
private UserService userSvc;
#Autowired
#Qualifier("roleService")
private RoleService roleSvc;
...
}
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations="/application-test-context.xml")
#Transactional
//#SpringApplicationConfiguration
#SpringBootTest
#Configurable
public abstract class BaseSpringAwareTest {
....
}
My spring context file 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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
>
<!-- import resource="classpath:/applicationContext.xml"/ -->
<context:component-scan base-package="com.olp"/>
<tx:annotation-driven />
<jpa:repositories base-package="com.olp.jpa" entity-manager-factory-ref="entityManagerFactory"/>
<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="persistenceUnitManager" ref="persistenceUnitMgr"/>
<property name="jpaDialect" ref="jpaDialect"/>
</bean>
<bean id="persistenceUnitMgr" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocation" value="classpath:persistence-test.xml"/>
<property name="defaultPersistenceUnitName" value="productHubTest"/>
<property name="packagesToScan">
<array value-type="java.lang.String">
<value>com.olp.jpa</value>
</array>
</property>
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
...
</beans>
I am getting this exception while executing the JUnits -
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: UserEntity is not
mapped [SELECT t FROM UserEntity t JOIN FETCH t.roles ORDER BY
t.userName ASC] at
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
at
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
at
org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:713)
at
org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:729)
at
org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ...
My entity classes are in child packages of the top level component scan mentioned - "com.olp"
package com.olp.jpa.domain.docu.um.model;
...
#Entity
#Table(name = "trl_users")
#Cacheable(true)
#NamedQueries({
#NamedQuery(....)
})
// ...
public class UserEntity extends MultiTenantLifeCycleEntity {
// ...
}
package com.olp.jpa.common;
#MappedSuperclass
public class MultiTenantLifeCycleEntity {
// ...
}
Couldn't identify the root cause. Any pointers will be highly appreciated.

Related

could not autowire no beans of type found

I new in java and i have 3 question about springboot in java
1 - Its my BaseRepository class
#Repository
#Transactional
public class BaseBaseRepository<Entity extends Base> implements IBaseRepository<Entity> {
private SessionFactory sessionFactory;
public BaseBaseRepository(SessionFactory sessionFactory) // this line give me an error : Could not autowire. No beans of 'sessionFactory' type found. when i put #Autowired nothing changed
{
this.sessionFactory = sessionFactory;
}
#Override
public Entity Add(Entity entity) {
try {
var session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(entity);
session.flush();
} catch (Exception e) {
throw e;
}
return entity;
}
// other method
}
2- My second question is its my application applicationContext-dataSource.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns="http://www.springframework.org/schema/beans"
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/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/datasource"/>
<property name="lookupOnStartup" value="true"/>
<property name="proxyInterface" value="javax.sql.DataSource"/>
</bean>
</beans>
and its my applicationContext-hibernate.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:p="http://www.springframework.org/schema/p" 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/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">
<import resource="applicationContext-dataSource.xml"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:mappingResources="com.payment.Repository.ModelAndMapper.BaseModel.Acceptor.Acceptor.hbm.xml">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="eventListeners">
<map>
<entry key="merge">
<bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/>
</entry>
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
<context:annotation-config/>
<tx:annotation-driven/>
<context:mbean-export/>
<bean id="BaseBaseRepository" class="com.payment.Repository.Implement.BaseBaseRepository"/>
</beans>
But in spring boot i have no web.xml to say use this config.
what should i do ?
3 -And last question Does it have any software that input my java model and give me hbm.xml file ?
Use the following code
#Configuration
#ImportResource({"classpath*:applicationContext-hibernate.xml"})
public class HibernateConfiguration {
}

Spring #Transactional method doesn't rollback

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.

Spring/JPA data persisting in unit test but not in application

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().

Spring 3.2 Hibernate No active transaction

I'm new to Spring, using version 3.2 with Hibernate 4.1.9Final, it seems that #Transactional annotations are being ignored, i've tried to set it on the controller method, service method and dao, no success
I've included the packages in
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
<display-name>
Spring
</display-name>
<description>
Spring Test
</description>
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springapp-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
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-3.2.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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<context:component-scan base-package="com.test.web.controllers,com.test.service.impl" />
<context:annotation-config />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="myDataSource" 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/test?zeroDateTimeBehavior=convertToNull"/>
<property name="username" value="medi"/>
<property name="password" value="tech"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingLocations" value="classpath*:com/test/model/hbm/**/*.hbm.xml" />
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.current_session_context_class=thread
</value>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" mode="proxy"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="categoryDAO" class="com.test.dao.hibernate.HibernateCategoryDAO">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="categoryService" class="com.test.service.impl.Categories" scope="singleton">
<property name="dao" ref="categoryDAO"></property>
</bean>
</beans>
My Test Controller
public class HelloController {
#Autowired
private CategoryService categories;
public HelloController() {
System.out.println("test!!!");
}
public void setCategoryService(CategoryService categories) {
this.categories = categories;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
#Transactional
public String getIndex() {
Category c = new Category();
c.setName("Test");
categories.save(c);
return "index";
}
}
Stacktrace:
org.hibernate.HibernateException: save is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
at $Proxy19.save(Unknown Source)
at com.test.dao.hibernate.HibernateCategoryDAO.save(HibernateCategoryDAO.java:20)
at com.test.service.impl.Categories.save(Categories.java:21)
at com.test.web.controllers.HelloController.getIndex(HelloController.java:36)
at com.test.web.controllers.HelloController$$FastClassByCGLIB$$aa12a3a3.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
Removed hibernate.current_session_context_class=thread and it works. Spring injecting its own session context managing implementation when using Spring transaction support layer?
You are using #Transactional in the controller layer. It should be in your Service layer.
Make Categories.save method #Transactional and you might get this error away.
Try to add <context:component-scan base-package="your package here">
Looks like it just can't find annotations

spring jpa hibernate writing to the DB fails - no transaction

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.

Categories

Resources