UnknownServiceException: Unknown service requested (Hibernate/Spring) - spring

This problem bothers me now for days ..
I'm trying to get the current session from my sessionFactor but receive an org.hibernate.service.UnknownServiceException: Unknown service requested exception.
I have no idea what causes this or what this exception does mean in particular. The exception gets thrown as getCurrentSession()gets called.
#Component
public class RestaurantOwnerRepository implements RestauranOwnerDAO {
private SessionFactory sessionFactory;
public RestaurantOwnerRepository(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
#Transactional
public List<Restaurant> getAvailableRestaurants(String sessionId) {
Session session = sessionFactory.getCurrentSession();
// ..
}
}
which I am calling in my servlet:
#Configurable
public class RestaurantInformationServiceImpl extends XsrfProtectedServiceServlet implements RestaurantInformationService {
private static final long serialVersionUID = -4088840947018614411L;
private final static Logger logger = Logger.getLogger(RestaurantInformationServiceImpl.class);
#Autowired
public RestauranOwnerDAO restaurantOwnerRepository;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/appServlet/servlet-context.xml");
this.restaurantOwnerRepository = (RestauranOwnerDAO)applicationContext.getBean("restaurantOwnerRepository");
((ConfigurableApplicationContext)applicationContext).close();
}
#Override
public List<RestaurantDTO> getAvailableRestaurants() {
List<Restaurant> availableRestaurants = restaurantOwnerRepository.getAvailableRestaurants(getSessionId());
// ..
}
}
This is my servlet-context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<context:component-scan base-package="com.mahlzeit.web.server" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mahlzeit_db" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate-webserver.cfg.xml" />
</bean>
<!-- <tx:annotation-driven transaction-manager="transactionManager"/> -->
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="restaurantOwnerRepository" class="com.mahlzeit.web.server.dao.RestaurantOwnerRepository">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
</beans>
And this my hibernate-webserver.cfg.xml file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/mahlzeit_db</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Batch size -->
<!-- <property name="hibernate.jdbc.batch_size">20</property> -->
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<property name="format_sql">false</property>
<!-- Drop and re-create the database schema on startup -->
<!-- <property name="hibernate.hbm2ddl.auto">create-drop</property> -->
<!-- Run Hibernate in update mode -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Bind the getCurrentSession() method to the thread -->
<!-- <property name="current_session_context_class">thread</property> -->
<!-- Mappings ... -->
</session-factory>
</hibernate-configuration>
Error message/stack trace:
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.util.List com.mahlzeit.web.shared.service.restaurant.RestaurantInformationService.getAvailableRestaurants()' threw an unexpected exception: org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:415)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:605)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:333)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:303)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:373)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
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(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:126)
at org.hibernate.internal.AbstractSessionImpl.getJdbcConnectionAccess(AbstractSessionImpl.java:261)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.<init>(JdbcCoordinatorImpl.java:97)
at org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl.<init>(TransactionCoordinatorImpl.java:87)
at org.hibernate.internal.SessionImpl.<init>(SessionImpl.java:254)
at org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1609)
at org.hibernate.internal.SessionFactoryImpl.openSession(SessionFactoryImpl.java:973)
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:122)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:988)
at com.mahlzeit.web.server.dao.RestaurantOwnerRepository.getAvailableRestaurants(RestaurantOwnerRepository.java:62)
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:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:266)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy50.getAvailableRestaurants(Unknown Source)
at com.mahlzeit.web.server.service.restaurant.RestaurantInformationServiceImpl.getAvailableRestaurants(RestaurantInformationServiceImpl.java:50)
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:606)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:587)
... 25 more
I just don't have any idea how to solve that problem.
Any help on this would be appreciated!

So, I don't know why it came up to me to comment out the line
((ConfigurableApplicationContext)applicationContext).close();
in init(ServletConfig config) as such
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/appServlet/servlet-context.xml");
this.restaurantOwnerRepository = (RestauranOwnerDAO)applicationContext.getBean("restaurantOwnerRepository");
//((ConfigurableApplicationContext)applicationContext).close();
}
but not closing the application context sure did help here..
I didn't thought about this. I just followed the warning in Eclipse
Resource leak: 'applicationContext' is never closed
and closed it without thinking obviously..

Related

Erreur java.lang.NullPointerException in jsf managed bean

Hello i have Started a spring jsf project when i run the first page jsf i recived this error:
java.lang.NullPointerException
com.project.formation.bean.StudentBean.addStudent(StudentBean.java:31)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.apache.el.parser.AstValue.invoke(AstValue.java:278)
org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
javax.faces.component.UICommand.broadcast(UICommand.java:315)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
can u help me and thank you !
the problem is in the jsf managed bean exactly in the addStudent() method:
public class StudentBean implements Serializable {
#Autowired
private StudentService studentService;
private Student student;
public StudentBean() {
student = new Student();
}
public void addStudent() {
studentService.add(student);//line 31
student=new Student();
}
public List<Student> getStudentList() {
return studentService.findAll();
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
My Dao bean code is :
public class StudentDaoImpl implements StudentDao {
#PersistenceContext
private EntityManager em;
#Override
public void add(Student student) {
em.persist(student);
}
#SuppressWarnings("unchecked")
#Override
public List<Student> findAll() {
Query query=em.createQuery("select s from Student s");
return query.getResultList();
}
}
and the complete spring xml file configuration: applicationContext.xml is :
<?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:tx="http://www.springframework.org/schema/tx"
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-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- bean of data source -->
<bean id="datasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/Student"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>
<!-- bean of persistence manager -->
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="datasource"></property>
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
</bean>
<!-- bean definition entityManagerFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager"></property>
<property name="persistenceUnitName" value="UP_STUDENT"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:annotation-config></context:annotation-config>
<bean id="studentDao" class="com.project.formation.dao.StudentDaoImpl"/>
<bean id="studentService" class="com.project.formation.service.StudentServiceImpl"/>
</beans>
I suspect your StudentService is not autowired and is null, check to make sure it is annotated with #Service or #component so it is known to spring context.
generally you should mark it required=true if your app requires a bean to function.
you dont have a getter and setter for your student service in your StudenBean

BeanCreationException spring hibernate jsf

So I have a huge update. I finally got my sessionFactory to initialize and not be null. I still have (hopefully) the last problem.
I am getting the following stacktrace when I go to store the data in the DAO file.
javax.faces.el.EvaluationException: org.hibernate.HibernateException: No Session found for current thread
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:931)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:941)
at com.scott.common.CustomerDAO.saveToDb(CustomerDAO.java:25)
at com.scott.common.CustomerBackingBean.save(CustomerBackingBean.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 24 more
<?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="backingBean" class="com.scott.common.CustomerBackingBean"
scope="request">
<property name="customer" ref="customerPojo" />
<property name="customerDao" ref="customerDao" />
</bean>
<bean id="customerPojo" class="com.scott.common.Customer"></bean>
<bean id="customerDao" class="com.scott.common.CustomerDAO">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="mysql://localhost:3306/scottdb" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.scott.common.Customer</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
</beans>
package com.scott.common;
import org.hibernate.SessionFactory;
public class CustomerDAO
{
private SessionFactory sessionFactory;
/**
* #return the sessionFactory
*/
public SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* #param sessionFactory the sessionFactory to set
*/
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void saveToDb(Customer customer)
{
getSessionFactory().getCurrentSession().save(customer);
}
}
As your current pom file is only using the hibernate-core dependency, it seems that the cache extension is not being added.
Try adding the hibernate-ehcache dependency to your pom file:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.1.7.Final</version>
</dependency>

Not able to run sql query with Mybatis

I am trying to run a simple sql query using mybatis but its giving me following exception
java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.mycom.myproject.db.mybatis.dao.UserMapper.countByExample
org.apache.ibatis.session.Configuration$StrictMap.get(Configuration.java:660)
org.apache.ibatis.session.Configuration.getMappedStatement(Configuration.java:495)
org.apache.ibatis.session.Configuration.getMappedStatement(Configuration.java:488)
org.apache.ibatis.binding.MapperMethod.setupCommandType(MapperMethod.java:236)
org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:71)
org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:39)
$Proxy9.countByExample(Unknown Source)
com.mycom.myproject.controller.LoginController.login(LoginController.java:39)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
My UserMapper.xml is
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.mycom.myproject.db.mybatis.dao.UserMapper" >
<select id="countByExample" resultType="int">
select count(*) from users
</select>
</mapper>
My UserMapper is
public interface UserMapper {
int countByExample();
}
I am trying to access it in my LoginController
public class LoginController
{
static final Logger logger = Logger.getLogger(LoginController.class);
#Autowired
private UserMapper userMapper;
#RequestMapping("/login")
public ModelAndView login(#ModelAttribute User userBean, Model model){
int count = userMapper.countByExample();
System.out.println("Count: "+ count);
return new ModelAndView("login", "userBean", userBean);
}
}
My spring-servlet.xml file is
<?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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:annotation-config />
<context:component-scan
base-package="com.mycom.myproject" />
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/mydatabase"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- Declare a transaction manager -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="datasource" />
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource" />
</bean>
<!-- scan for mappers and will automatically scan the whole classpath for xmls -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
<property name="basePackage" value="com.mycom.myproject.db.mybatis.dao" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
I don't know why this error is coming.
Taking a look to the error
Mapped Statements collection does not contain value for com.mycom.myproject.db.mybatis.dao.UserMapper.countByExample
it looks like myBatis is not finding your query. That is probably becuase it is not finding your xml mapped. It should be in com.mycom.myproject.db.mybatis.dao package according with your configuration:
<!-- scan for mappers and will automatically scan the whole classpath for xmls -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
<property name="basePackage" value="com.mycom.myproject.db.mybatis.dao" />
</bean>
In the project structure, UserMapper.java and UserMapper.xml can be in different folders (if you want to separate xml from java files) but they should be in a package with the same name and they should be combined in the same folder in the war build process because they both should be available in the classpath according with your configuration.

Object org.tts.maqraa.data.Daralquran#1e20120 is not a known entity type

I'm facing the following problem when i persist an entity using entity manager that acquired by Spring.
java.lang.IllegalArgumentException: Object: org.tts.maqraa.data.Daralquran#183eae7 is not a known entity type.
javax.faces.FacesException: #{configurationChecker.check}: java.lang.IllegalArgumentException: Object: org.tts.maqraa.data.Daralquran#183eae7 is not a known entity type.
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: javax.faces.el.EvaluationException: java.lang.IllegalArgumentException: Object: org.tts.maqraa.data.Daralquran#183eae7 is not a known entity type.
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 23 more
Caused by: java.lang.IllegalArgumentException: Object: org.tts.maqraa.data.Daralquran#183eae7 is not a known entity type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.mergeCloneWithReferences(UnitOfWorkImpl.java:3484)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.mergeCloneWithReferences(RepeatableWriteUnitOfWork.java:378)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.mergeCloneWithReferences(UnitOfWorkImpl.java:3455)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.mergeInternal(EntityManagerImpl.java:486)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.merge(EntityManagerImpl.java:463)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365)
at $Proxy8.merge(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
at $Proxy8.merge(Unknown Source)
at org.tts.maqraa.service.AbstractMaqraaService.store(AbstractMaqraaService.java:60)
at org.tts.maqraa.service.DarAlQuranService.createNewDarAlQuran(DarAlQuranService.java:47)
at org.tts.maqraa.service.test.ConfigurationChecker.check(ConfigurationChecker.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.el.parser.AstValue.invoke(AstValue.java:264)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 24 more.
Where i'm using the following technologies
Apache Tomcat 7.
Eclipse Link 2.3.2.
Spring 3.0.
JSF 2.0 Mojarra.
Also you can find the Daralquran entity to ensure that the entity is mapped properly.
#Entity
public class Daralquran implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Temporal( TemporalType.DATE)
#Column(name="Established_Date")
private Date establishedDate;
#Column(name="Full_Name")
private String fullName;
#Column(name="Mobile_Number")
private String mobileNumber;
private String note;
#Column(name="Phone_no")
private String phoneNo;
//bi-directional many-to-one association to City
#ManyToOne(cascade={CascadeType.ALL})
#JoinColumn(name="city_Id")
private City city;
//bi-directional many-to-one association to Country
#ManyToOne(cascade={CascadeType.ALL})
#JoinColumn(name="country_Id")
private Country country;
//bi-directional many-to-one association to User
#ManyToOne(cascade={CascadeType.ALL})
#JoinColumn(name="supervisor_id")
private User user;
//bi-directional many-to-many association to User
#ManyToMany(mappedBy="daralqurans2", fetch=FetchType.EAGER)
private List<User> users;
public Daralquran() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public Date getEstablishedDate() {
return this.establishedDate;
}
public void setEstablishedDate(Date establishedDate) {
this.establishedDate = establishedDate;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getMobileNumber() {
return this.mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
public String getPhoneNo() {
return this.phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public City getCity() {
return this.city;
}
public void setCity(City city) {
this.city = city;
}
public Country getCountry() {
return this.country;
}
public void setCountry(Country country) {
this.country = country;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public List<User> getUsers() {
return this.users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
Also you can find the content of persistence.xml file
<?xml version="1.0" encoding="UTF-8" ?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="Maqraa">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.tts.maqraa.data.DarAlquranManager</class>
<class>org.tts.maqraa.data.DoorAlquranGM</class>
<class>org.tts.maqraa.data.QuranTeacher</class>
<class>org.tts.maqraa.data.ScientificOfficer</class>
<class>org.tts.maqraa.data.SystemAdmin</class>
<class>org.tts.maqraa.data.City</class>
<class>org.tts.maqraa.data.Country</class>
<class>org.tts.maqraa.data.Daralquran</class>
<class>org.tts.maqraa.data.HalaqaAchievement</class>
<class>org.tts.maqraa.data.HalaqaAssociation</class>
<class>org.tts.maqraa.data.Halaqa</class>
<class>org.tts.maqraa.data.MemorizationProgram</class>
<class>org.tts.maqraa.data.Permission</class>
<class>org.tts.maqraa.data.Phase</class>
<class>org.tts.maqraa.data.PhasesAttendance</class>
<class>org.tts.maqraa.data.Recitation</class>
<class>org.tts.maqraa.data.Role</class>
<class>org.tts.maqraa.data.Student</class>
<class>org.tts.maqraa.data.User</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/maqraa" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="eclipselink.ddl-generation" value="none" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
</properties>
</persistence-unit>
</persistence>
Also you can find the spring meta data configuration maqraa-module-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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/maqraa" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Maqraa" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect" ref="jpaDialect" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver" />
</property>
</bean>
<bean id="darAlquranService" class="org.tts.maqraa.service.DarAlQuranService"></bean>
<bean id="configurationChecker" class="org.tts.maqraa.service.test.ConfigurationChecker"></bean>
</beans>
So, can anyone help me make the em works properly.
Thanks
Mohammed Amr.
This is a class loader issue, you somehow have two different versions of the same class loaded.
Ensure you have not deployed this class in two different places, and have Spring configured correctly. Perhaps try some of the Spring examples.
Are you redeploying? If you have not closed the old EntityManagerFactory you could get this error. Try restarting the server.
Do all of your classes have the same error, or do some work?
I get it :),
Cause i use tomcat 7 for application running, and it is not an EE contrainer, therefore it must use "LocalEntityManagerFactory" rather than "LocalContainerEntityManagerFactory".
By this you will be able to invoke the entity manager methods and by taken a transaction in your consideration.
Totally, this is the last maqraa-module-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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config />
<!-- <context:component-scan base-package="org.tts.maqraa.data" annotation-config="true"/> -->
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/maqraa" />
<property name="username" value="maqraa" />
<property name="password" value="maqraa" />
</bean>
<bean id="jpaDialect"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Maqraa" />
</bean>
<bean id="configurationChecker" class="org.tts.maqraa.service.test.ConfigurationChecker"></bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<!-- Activates various annotations to be detected in bean classes for eg
#Autowired -->
<!-- <context:annotation-config/> -->
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
Thanks all,
Mohammed Amr.
Maybe you need to specifically GenerationType , not use the GenerationType.Auto.Try it.I am not sure.The same case is here

Eclipselink and Spring 3.1

I have got Hibernate working but I am trying to change to Eclipselink. I have been searching for a solution for this but without result. People suggest putting these two(not together)
<class>no.mesta.driftslogg.model.Person</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
in persistence.xml
persitence.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="cccPersistenceUnit">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
</properties>
</persistence-unit>
application-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:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
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">
<!-- Spring transaction manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entityManagerFactory-ref="entityManagerFactory" />
<!-- JPA Hibernate shared entity manager -->
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean" p:entityManagerFactory-ref="entityManagerFactory" /
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="cccPersistenceUnit" />
<property name="jpaDialect" ref="jpaDialect" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
</bean>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver" />
</property>
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
<!-- <property name="showSql" value="true" /> -->
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/driftslogg" />
<property name="user" value="root" />
<property name="password" value="root" />
<property name="acquireIncrement" value="5" />
<property name="idleConnectionTestPeriod" value="60" />
<property name="maxPoolSize" value="100" />
<property name="maxStatements" value="50" />
<property name="minPoolSize" value="10" />
</bean>
Dao class
package no.mesta.driftslogg.dao.jpa;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import no.mesta.driftslogg.dao.PersonDao;
import no.mesta.driftslogg.model.Person;
import org.springframework.stereotype.Repository;
#Repository
public class PersonDaoJpa implements PersonDao {
protected EntityManager entityManager;
#PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
#Override
public Person save(Person person) {
if (person.getId() != null) {
return entityManager.merge(person);
} else {
entityManager.persist(person);
}
return person;
}
}
The entity class
package no.mesta.driftslogg.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The error
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Object: Todo [summary=This is a test, description=This is a test] is not a known entity type.
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)
com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)
root cause
java.lang.IllegalArgumentException: Object: Todo [summary=This is a test, description=This is a test] is not a known entity type.
org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4169)
org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:440)
no.mesta.driftslogg.dao.jpa.PersonDaoJpa.save(PersonDaoJpa.java:45)
no.mesta.driftslogg.service.impl.PersonServiceImpl.savePerson(PersonServiceImpl.java:20)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
$Proxy15.savePerson(Unknown Source)
no.mesta.driftslogg.controller.HomeController.home(HomeController.java:31)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)
com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)
Your error is on a "Todo" object, not a person. Ensure you have mapped all of the related objects.
You need to put the no.mesta.driftslogg.model.Person in your persistence.xml, you do not have this.
Rather than using the SimpleLoadTimeWeaver (I couldn't get that to work either), I use
<context:load-time-weaver/>
That requires the use of the java agent from spring-instrument, so you will have to start the JVM with an agument telling it where to find that. Something like
-javaagent:spring-instrument-3.1.1.RELEASE.jar

Resources