Not able to getCurrentSession() from SessionFactory , Getting HibernateException - spring

Its my first very simple Spring-Hibernate application.
i am getting this
'Could not obtain transaction-synchronized Session for current thread ' error
when i am trying to get current session from SessionFactory.
I tried following things..
used #Repository , #Transactional in my dao.
configured TransactionManager.
used # Entity on my entity class.
my root-context.xml
<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:mvc="http://www.springframework.org/schema/mvc"
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">
<!-- <context:property-placeholder
location="classpath:../properties/db.properties" /> -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/hib" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.nin.entity" />
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.default_schema">hib</prop>
</props>
</property>
<tx:annotation-driven transaction-manager="TransactionManager" />
<bean id="TransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
My dispatcherServlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-
context-3.1.xsd">
<context:component-scan base-package="com.nin"></context:component-scan>
<mvc:annotation-driven/>
</beans>
My Dao class
package com.nin.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.nin.entity.Student;
#Repository
public class DaoImpl {
#Autowired
private SessionFactory sf;
#Transactional
public void register (Student st){
sf.getCurrentSession(); //Getting Error at this line.
// Session session = sf.getCurrentSession();
// session.save(st);
}
}
lastly my entity class
package com.nin.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student {
#Column(name="name")
private String name;
#Id
#Column(name="rollno")
private String rollno;
#Column(name="password")
private String password;
#Column(name="city")
private String city;
public Student(){};
//and getters and setters..
Thanks in advance and sorry for my English & representation of question.

The problem is that your Hibernate and transaction configuration is in the configuration file loaded by the ContextLoaderListener. Whereas your components are loaded by the DispatcherServlet due to the <component-scan /> in that file.
When using things like transactions those are applied through AOP. AOP is applied through post processing beans. Post processing only applies to beans in the same context, else you might get strange results.
As you haven't 2 contexts, the AOP stuff is in a different one then the actual components you want to apply AOP to.
You can either put everything in a single context or move the <context:component-scan /> to the configuration containing the transactional configuration.
Note: If you have the same <component-scan /> in the configuration file all of your components will be loaded twice and as the nearest to the component (in this case controller) is being used you have the same problem.

Related

test hibernate entities with spring

I try to tests how hibernate Entities are persisted to database. I have 5 tests for 3 Entitites. All my attempts are unsuccessful((( I tried to use #Transactional annotation to bind each test to one transaction. But I could not (tried all combinations). Now I try to test it manually creating sessions and transactions. But now problem is that I dont know how to create one session for all tests. I tried #BeforeClass, but here problem is that it is static and I use Spring beans for session creation. Any ideas how I can test hibernate Entities?
You can use a dedicated database like HSQLDB for testing you entities via DAO test classes.
You will need a:
Maven test profile
Spring configuration file (test context)
Script SQL to insert some data
DAO class test.
Maven test profile :
<profile>
<id>test</id>
<properties>
<jpa.dialect>org.springframework.orm.jpa.vendor.HibernateJpaDialect</jpa.dialect>
<jpa.vendor.adapter>HibernateJpaVendorAdapter</jpa.vendor.adapter>
<jdbc.dialect>org.hibernate.dialect.HSQLDialect</jdbc.dialect>
<jdbc.url>jdbc:hsqldb:mem:testDatabase</jdbc.url>
<jdbc.driver>org.hsqldb.jdbcDriver</jdbc.driver>
<jdbc.username>sa</jdbc.username>
<jdbc.password></jdbc.password>
<jdbc.format_sql>true</jdbc.format_sql>
<jdbc.show_sql>true</jdbc.show_sql>
<!-- import.sql is read : it must have this name and be in classpath -->
<jpa.generateDdl>true</jpa.generateDdl>
<hibernate.format_sql>true</hibernate.format_sql>
<hibernate.hbm2ddl.auto>create</hibernate.hbm2ddl.auto>
</properties>
</profile>
Spring test-applicationContext.xml 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: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-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!-- enables interpretation of the #PersistenceUnit/#PersistenceContext
annotations providing convenient access to EntityManagerFactory/EntityManager -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<context:component-scan base-package="foo.bar.dao">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Repository" />
</context:component-scan>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="jpaLibrary" />
<property name="jpaDialect">
<bean class="${jpa.dialect}" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.${jpa.vendor.adapter}">
<property name="showSql" value="${jdbc.show_sql}" />
<property name="databasePlatform" value="${jdbc.dialect}" />
<!-- On genere la BDD au demarrage -->
<property name="generateDdl" value="${jpa.generateDdl}" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager" />
<context:spring-configured />
<context:annotation-config />
</beans>
import.sql (authors for instance):
INSERT INTO `testDatabase`.`authors`(author_id, name) VALUES
(1, "JRR Tolkien"),
(2, "Albert Camus"),
(3, "Victor Hugo");
...
Finally, the class to test your DAO (then entities) :
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import foo.bar.dao.BookDao;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "/test-applicationContext.xml" })
public class BookDaoTest extends AbstractTransactionalJUnit4SpringContextTests {
#Autowired
private BookDao bookDao;
private int initialSize = 0;
#Before
public void init() {
initialSize = bookDao.findAll().size();
}
#Test
public void getAllBooks() {
assertEquals(12, initialSize);
}
...
}

Cannot autowire Spring Data Repository

I'm creating a simple application with Spring, Hibernate and MySQL database. I've done some research, but no answer was accurate. I have a repository interface, which is an extension of BaseCrudRepository, which extends ReadOnlyRepository, which is an extension of org.springframework.data.repository.Repository.
Code is as below:
package dziecko.repositories;
import dziecko.models.AreaDate;
import dziecko.utils.BaseCrudRepository;
public interface AreaDateRepository extends BaseCrudRepository<AreaDate, Integer> {}
AreaDate is a simple entity:
#Entity
#Table(name = "AREADATES")
public class AreaDate extends AbstractBase implements DtoGenerator<AreaDateDto> {
private static final long serialVersionUID = -2956040373671316338L;
#Column(name = "START_TIME")
private Date startTime;
#Column(name = "END_TIME")
private Date endTime;
#Column(name = "ALARM", nullable = true)
private Boolean alarm;
public AreaDate() {
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
public Boolean getAlarm() {
return alarm;
}
#Override
public AreaDateDto createDto() {
return new AreaDateDto(id, startTime, endTime, alarm);
}
}
Here is my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
app-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:beans="http://www.springframework.org/schema/beans" 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/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/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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- Enable #Controller annotation support -->
<mvc:annotation-driven />
<jpa:repositories base-package="dziecko.repositories" />
<context:annotation-config />
<!-- Scan classpath for annotations (eg: #Service, #Repository etc) -->
<context:component-scan base-package="dziecko.rests, dziecko.services">
<context:exclude-filter expression="org.springframework.web.bind.annotation.RestController" type="annotation" />
</context:component-scan>
<!-- JDBC Data Source. -->
<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://127.0.0.1:3306/dziecko" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="validationQuery" value="SELECT 1" />
</bean>
<!-- Hibernate Session Factory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan">
<array>
<value>dziecko.models</value>
</array>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="jadira.usertype.autoRegisterUserTypes">true</prop>
<prop key="jadira.usertype.databaseZone">jvm</prop>
<prop key="hibernate.id.new_generator_mappings">true</prop>
</props>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
The problem is that even this simple test fails, because repository which is supposed to be autowired is null:
package dziecko.tests;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import org.testng.annotations.Test;
import dziecko.repositories.AreaDateRepository;
public class SpringConfigurationTest {
#Autowired
private AreaDateRepository adRepo;
#Test
public void shouldWireComponents() {
Assert.assertNotNull(adRepo);
}
}
java.lang.AssertionError: expected object to not be null
All entities are created inside the database. I just can't figure out how to configure those Spring repositories properly. Everything seems to be done similar to http://docs.spring.io/spring-data/data-commons/docs/1.5.1.RELEASE/reference/html/repositories.html. Anyone has an idea how autowiring can be fixed here?
This is happening because your test class is Spring unaware. You need to:
include spring-test jar in your (test) classpath via Maven dependency or other means
From your test I can see you are using TestNG so the above jar will make for you available the TestNG Spring test runner:
Annotate your class with (supposing you don't have test context. That would have been a better practice btw):
#ContextConfiguration(locations = { "classpath:app-context.xml" })
public class SpringConfigurationTest extends AbstractTestNGSpringContextTests
{
//...
}
So I had app-context.xml file in WEB-INF folder and I didn't attach this context to test. Working version:
#ContextConfiguration("/META-INF/app-context.xml")
public class SpringConfigurationTest extends AbstractTestNGSpringContextTests {
#Autowired
private AreaDateRepository adRepo;
#Test
public void shouldWireComponents() {
Assert.assertNotNull(adRepo);
}
}

org.hibernate.HibernateException: save is not valid without active transaction

I have a problem to save the data with hibernate from Spring.
When I save data get error:
Exception in thread "main" org.hibernate.HibernateException: save is not valid without active transaction
https://gist.github.com/RuzievBakhtiyor/f3009dbc6a9c31090b59
Spring beans config:
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<import resource="hibernate.xml"/>
<import resource="dataSource.xml"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<context:component-scan base-package="neron" />
Hibernate config bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd">
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="neron.models" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
DataSource config bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd">
<bean name="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="root" />
<property name="password" value="123456789" />
</bean>
</beans>
TestDao:
package neron.dao.Impl;
import neron.dao.TestDao;
import neron.models.Test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
#Transactional
#Repository("testDao")
public class TestDaoImpl implements TestDao {
SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session getCurrentSession()
{
return (Session)sessionFactory.getCurrentSession();
}
public void save(Test test) {
getCurrentSession().save(test);
}
public Test findById(int id) {
return (Test) getCurrentSession().get(Test.class,id);
}
}
You need to do db update operation (insert, update, delete) within transaction boundary .
Session session = getCurrentSession();
Transaction trans = session.beginTransaction(); //begin transaction
//db operation
session.save(test)
trans.commit(); //end transaction
OR
For annotation support, in your spring config bean, add this
<tx:annotation-driven transaction-manager="transactionManager" mode="proxy" proxy-target-class="true" />
Remove this tag from sessionFactory -> hibernateProperties
<property name="hibernate.current_session_context_class">thread</property>

get Null pointer Exception when try to access model class in dwr function

My SessionFactory object is #Autowired
package com.ravi.dao.daoImpl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ravi.dao.UserDao;
import com.ravi.model.User;
#Repository("userDao")
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public List<User> listUsers()
{
System.out.println("UserDaoImpl - listUsers");
return (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class).list();
}
#Override
public void saveUser(User user)
{
System.out.println("UserDaoImpl - saveUser");
sessionFactory.getCurrentSession().saveOrUpdate(user);
}
#SuppressWarnings("unchecked")
#Override
public List<User> getUserByUserEmail(String userEmail)
{
System.out.println("UserDaoImpl - getUserByUserEmail");
return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail").setString("userEmail",userEmail).list();
}
#SuppressWarnings("unchecked")
#Override
public List<User> validateLoginUser(String userEmail, String password)
{
System.out.println("userEmail -- "+userEmail+" password --"+password);
System.out.println("UserDaoImpl - validateLoginUser");
return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail and password=:password").setString("userEmail", userEmail).setString("password",password).list();
}
}
i create on dwr function which is below.
package com.ravi.dwr;
import java.util.List;
import com.ravi.dao.daoImpl.UserDaoImpl;
import com.ravi.model.User;
public class ForgotPwd
{
public void sendMail(String EmailId)
{
System.out.println("DWR Called.");
UserDaoImpl userDaoImpl=new UserDaoImpl();
List<User> lstUser=userDaoImpl.getUserByUserEmail(EmailId);
User user=lstUser.get(0);
System.out.println("DWR Called.-- userEmail :"+user.getUserEmail());
}
}
when i want to try to print userEmail . null pointer exception is generated # return sessionFactory.getCurrentSession().createQuery("from User where userEmail=:userEmail").setString("userEmail",userEmail).list(); this point.
my spring-servlet.xml cofiguration.
<?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" 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-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="com.ravi"/>
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<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="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<!-- <bean id="sessionFactory" -->
<!-- class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> -->
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.ravi.model.User</value>
<value>com.ravi.model.Language</value>
<value>com.ravi.model.Questions</value>
<value>com.ravi.model.QuestionOptions</value>
<value>com.ravi.model.Admin</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="SessionFactory" ref="sessionFactory" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
in my project i used Annotation. is there any way to get user model data in dwr function.
or is there any process which automatically initialized (inject) when i try to use DAO class)
i don't want to remove #Autowired annotation in sessionFactory object. so please suggest me the best way to access or configure dwr function. other way i tried without using #Autowired annotation but in that case i have to entry all bean class in my spring-servlet.xml and also configure. hibernate.cfg.xml file.
in my project i used Annotation. is there any way to get user model data in dwr function.
or is there any process which automatically initialized (inject) when i try to use DAO class)
here i explain whole process. thank you in advance.
below error is generated when i am try to access userDaoImpl function. it is error show that session factory object is not initialized.
on more time i cleared that this is DWR function. which try to access sessionFactory instance.
without interacting controller.
UserLoginController --> showUserLogin
INFO (org.directwebremoting.log.startup:157) - Starting: DwrServlet v3.0.0-RC2-final-312 on Apache Tomcat/7.0.50 / JDK 1.7.0_10 from Oracle Corporation at `enter code here`/OnlineQuestion
DWR Called.
INFO (org.directwebremoting.log.accessLog:427) - Method execution failed:
java.lang.NullPointerException
at com.ravi.dwr.ForgotPwd.sendMail(ForgotPwd.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.directwebremoting.impl.CreatorModule$1.doFilter(CreatorModule.java:229)
at org.directwebremoting.impl.CreatorModule.executeMethod(CreatorModule.java:241)
at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:379)
at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:332)
at org.directwebremoting.dwrp.BaseCallHandler.handle(BaseCallHandler.java:104)
at org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:120)
at org.directwebremoting.servlet.DwrServlet.doPost(DwrServlet.java:141)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChai
here i explain whole process. thank you in advance.
below error is generated when i am try to access userDaoImpl function. it is error show that session factory object is not initialized.
on more time i cleared that this is DWR function. which try to access sessionFactory instance.
without interacting controller.
Assuming you want to use Spring MVC with DWR, try following code:
WEB-INF/web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
WEB-INF/spring-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
...
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
...
http://www.directwebremoting.org/schema/spring-dwr
http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd">
<dwr:controller id="dwrController" />
<dwr:annotation-scan base-package="com.ravi.dwr" />
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="mappings">
<props>
<prop key="/dwr/**/*">dwrController</prop>
</props>
</property>
</bean>
<context:component-scan base-package="com.ravi" />
...
</beans>
ForgotPwd.java
package com.ravi.dwr;
...
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
...
#RemoteProxy
public class ForgotPwd {
#Autowired
private UserDaoImpl userDaoImpl;
...
#RemoteMethod
public void sendMail(String EmailId) {
System.out.println("DWR Called.");
List<User> lstUser=userDaoImpl.getUserByUserEmail(EmailId);
...
}
...
}

Spring data JPA java.lang.IllegalArgumentException: Not an entity

I have created spring data JPA sample project. I used eclips for this. There are two projects, one is domain object project which has only annotated entity classes. Other project is actual spring data jpa project and it has a dependency for the project one. Actually it gets domain project entity classes via maven dependency.
Project 1 : hrm-domain
Entity class :
package com.hrm.ws.data.domain;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
#Entity(name = "Employee")
#Table(name = "employee")
#Inheritance(strategy = InheritanceType.JOINED)
public class Employee {
protected long id;
protected String firstName;
protected String lastName;
/**
* Gets the value of the id property.
*
*/
#Id
#Column(name = "id", scale = 0)
#GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
Project 2 : hrm-ws-service
persistance-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: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/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<jpa:repositories base-package="com.hrm.ws.data.repository" />
<bean id="employeeDao" class="com.hrm.ws.data.repository.EmployeeRepositoryImpl"/>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="${jdbc.generateDdl}" />
<property name="showSql" value="${jdbc.showSql}"/>
</bean>
</property>
<property name="persistenceUnitName" value="jpa.sample" />
</bean>
</beans>
So the setup for my packages is as follows:
src/main/java - contains the spring repository
src/main/resources - contains application context
src/test/java - contains unit tests
And dependency for the project 1 (hrm-domain)
My problem is when I run this project I am getting error as follows:
... 38 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Not an entity: class com.hrm.ws.data.domain.Employee
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:149)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:102)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1429)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
... 40 more
**Caused by: java.lang.IllegalArgumentException: Not an entity: class** com.hrm.ws.data.domain.Employee
at org.hibernate.ejb.metamodel.MetamodelImpl.entity(MetamodelImpl.java:160)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:52)
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:61)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:145)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:83)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:66)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:146)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:120)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:39)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142)
... 48 more
I am wondering about this issue, because when I put domain object (Employee.java) in my spring project it self rather separate jar it works fine. This issue only happens it gives as a separate jar. If any one has experience about scenario like that please give me a help.
I also had the same problem. Mine was that I didn't supply the packagesToScan property in the entityManagerFactory bean, so Spring couldn't load the Entities. Check out the emf bean declaration in your spring configuration xml. The following is a EMF declaration I hope it could help you to get rid the error:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="com.hrm.ws.data.domain" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
You're not scanning the com.hrm.ws.data.domain package for beans annotated with #Entity so the spring container has no knowledge of your entities and therefore producing an exception. Add the following lines to your persistance-context.xml config file:
<context:annotation-config />
<context:component-scan base-package="com.hrm.ws.data.domain" />
You'll also need to change your root xml element as follows so it the context elements are recognized:
<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"
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-3.0.xsd">
And, if you haven't already, add the spring-context dependency to your pom file.
Use one of the following option :-
context:component-scan
base-package="Your Base Package Name" in spring.xml file
set packagesToScan property on the entityManagerFactory
use persistence.xml and list all entities there.

Resources