org.hibernate.MappingException: Unknown entity: java.lang.Integer - java

I am doing a project on spring MVC with maven.I pass my data using Ajax to the controller.it is ok..but when i call the function for delete,i got org.hibernate.MappingException: Unknown entity: java.lang.Integer . below my codes..waiting for your reply
web.xml
<?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">
<servlet>
<servlet-name>AccPerSpring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AccPerSpring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-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: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-3.2.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-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Enable #Controller annotation support -->
<mvc:annotation-driven />
<!-- Map simple view name such as "test" into /WEB-INF/views/test.jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Scan classpath for annotations (eg: #Service, #Repository etc) -->
<context:component-scan base-package="com.gerrytan.pizzashop"/>
<!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and blank password. Change below if it's not the case -->
<!-- <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> -->
<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/mydatabase"/>
<property name="username" value="root"/>
<property name="password" value="kca#fnpl#12"/>
</bean>
<!-- Hibernate Session Factory -->
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<array>
<value>com.gerrytan.pizzashop</value>
</array>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
Accountsconttroller .java
package com.gerrytan.pizzashop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
#Controller
#RequestMapping(value="/account")
public class AccountsController {
#Autowired
private AccountService accountService;
#Autowired
private AccountDAO accountDao;
private Accounts accounts;
#RequestMapping(value="/list",method = RequestMethod.GET,produces="application/json")
#ResponseBody
public String getAllAccounts(ModelMap model){
model.addAttribute("count",accountDao.getRowCount());
model.addAttribute("allAddress",accountDao.getAccounts());
String json= new Gson().toJson(model);
return json;
}
#RequestMapping(value="/delete",method=RequestMethod.POST,produces="application/json")
#ResponseBody
public ModelMap deleteRow(ModelMap model,#RequestParam(value = "id", required = true) int id) {
System.out.println(id);
accountDao.delete(id);
model.addAttribute("messageKey", "1");
model.addAttribute("id", id);
return model;
}}
implimentation.java
#Override
public void delete(int id) {
getCurrentSession().delete(id);
System.out.println("fgfgfgfgf");
}
my error is when iam calling the function delete from controller

Notice the hibernate method getCurrentSession().delete(Object obj), not just give an id as parameter.
#Override
public void delete(int id) {
Account accounts = new Accounts();
// hibernate deletes objects by the primary key
accounts.setId(id);
getCurrentSession().delete(accounts);
}

The getCurrentSession() method would return an implementation of the session interface. Looking up the javadocs from 3.6 and further for Hibernate.
It supports 2 methods for deletion
void delete(Object object)
Remove a persistent instance from the datastore.
void delete(String entityName, Object object)
Remove a persistent instance from the datastore.
In your accountsDAO.delete() method, you are passing in a String id to the delete method.
You would have to fetch the Account that you want to delete and pass the Account object for deletion. What Jiang mentioned would work too.

Just add and replace with following code snippet in your AccountsDAO Implementation class
#Transactional
public void delete(int id) {
Account acc = new Account();
acc.setId(id);
Session session=sessionFactory.getCurrentSession();
session.delete(acc);
}

Simple solution : If you work with Spring Framework then just change in your Dao & Service layer method's parameter type. simply replace your 'Integer' parameter to 'Object' parameter. Eg : public void delete(int id) To replace >> public void delete(User user). your 'Unknown entity: java.lang.Integer' error will solve...

Related

No bean named 'transactionManager' available:

Request processing failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' available: No matching TransactionManager bean found for qualifier 'transactionManager' - neither qualifier match nor bean name match!
CustomerDAOImpl.java
package com.shadow.springdemo.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.shadow.springdemo.entity.Customer;
#Repository
public class CustomerDAOImpl implements CustomerDAO {
// need to inject the session factory
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<Customer> getCustomers() {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create a query
Query<Customer> theQuery =
currentSession.createQuery("from Customer", Customer.class);
// execute query and get result list
List<Customer> customers = theQuery.getResultList();
// return the results
return customers;
}
}
CustomerController
package com.shadow.springdemo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.shadow.springdemo.dao.CustomerDAO;
import com.shadow.springdemo.entity.Customer;
#Controller
#RequestMapping("/customer")
public class CustomerController {
// need to inject the customer dao
#Autowired(required = true)
private CustomerDAO customerDAO;
#RequestMapping("/list")
public String listcustomer(Model theModel) {
//get customer from dao
List<Customer> theCustomers = customerDAO.getCustomers();
//add customer to model
theModel.addAttribute("customers", theCustomers);
return "list-customer";
}
}
CustomerDAO
package com.shadow.springdemo.dao;
import java.util.List;
import com.shadow.springdemo.entity.Customer;
public interface CustomerDAO {
public List<Customer> getCustomers();
}
spring-mvc-crud-demo-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: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-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-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/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.shadow.springdemo" />
<!-- Add support for conversion, formatting and validation support -->
<tx:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC" />
<property name="user" value="student" />
<property name="password" value="student" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.shadow.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>spring-mvc-crud-demo</display-name>
<absolute-ordering />
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-crud-demo-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
referring Spring document
A minor difference between the two examples lies in the naming of the
TransactionManager bean: In the #Bean case, the name is "txManager"
(per the name of the method); in the XML case, the name is
"transactionManager". The <tx:annotation-driven/> is hard-wired to
look for a bean named "transactionManager"
hence in ur xml rename the bean myTransaction to transactionManager
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager" />

Java Spring MVC + Hibernate - sessionFactory "unsatisfied dependency" errror

I'm in the middle of creating my first Spring + Hibernate webapp and this is what I have in console:
Root Cause
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'quizDAOImpl': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.kubacki.entity.Quiz
I tried to find already existing solutions but nothing seems to work, would you be able to help me please?
I am not sure if the issue may be caused by bad XML configuration or some mistake in coding itself, from my perspective "sessionFactory" bean is correctly configured in XML and there should be no problem with injecting it.
Additionally, I'am using Maven for this project but I have already listed all spring + hibernate stuff in pom.xml
Here is my source code:
QuizDAO:
package com.kubacki.dao;
import java.util.List;
import com.kubacki.entity.Quiz;
public interface QuizDAO {
public Quiz getQuiz(int id);
public List<Quiz> getQuizzes();
}
QuizDAOImpl:
package com.kubacki.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.kubacki.entity.Quiz;
#Repository
public class QuizDAOImpl implements QuizDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public Quiz getQuiz(int id) {
Session tempSession = sessionFactory.getCurrentSession();
Quiz tempQuiz = tempSession.get(Quiz.class, id);
return tempQuiz;
}
#Override
public List<Quiz> getQuizzes() {
Session tempSession = sessionFactory.getCurrentSession();
Query<Quiz> theQuery = tempSession.createQuery("from quiz", Quiz.class);
List<Quiz> tempQuizzes = theQuery.getResultList();
return tempQuizzes;
}
}
Web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>WebApp</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-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: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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.kubacki" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" 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/quizdb?useSSL=false" />
<property name="user" value="root" />
<property name="password" value="admin" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.kubacki.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
As per the error
No identifier specified for entity: com.kubacki.entity.Quiz
I think, You are missing a field annotated with #Id in Quiz class. Each #Entity must have an #Id - this will be a primary key in your database.

Spring MVC Controller issue : No mapping found for HTTP request with URI

Yes. I know this is familiar issue. I have looked into other solutions and they didn't help me. I am trying to build Spring MVC Application with Spring 4, Hibernate 5, My Sql and Angular JS 1.x
Problem: As shown in image, When I run the application, it resolved to index.jsp file as expected, then I entered 'http://localhost:8080/TimeLee/user/test' to get web page 'adduser.html' . Boom, it throws following error 'No mapping found for HTTP request with URI [/TimeLee/WEB-INF/views/adduser.html] in DispatcherServlet with name 'mvc-dispatcher'. I checked controller mappings and everything looks good.
UserController:
package com.timelee.users.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.timelee.users.model.User;
import com.timelee.users.services.UserService;
#RestController
#RequestMapping("/user")
public class UserController
{
#Autowired
private UserService userService;
#RequestMapping(value="/adduser",method=RequestMethod.POST)
public void saveUser(#RequestBody User user)
{
userService.saveUser(user);
}
#RequestMapping(value="/getuser",method=RequestMethod.GET)
public #ResponseBody User getUser(#RequestParam("userId") String userId)
{
return userService.getUser(userId);
}
#RequestMapping(value="/test",method=RequestMethod.GET)
public ModelAndView test()
{
ModelAndView modelAndView=new ModelAndView("adduser");
return modelAndView;
}
#RequestMapping(value="/test2",method=RequestMethod.GET)
public String test2()
{
return "adduser";
}
}
web.xml
<web-app id="WebApp_ID" 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 Web MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-mvc-config.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
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-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/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.html</value>
</property>
</bean>
<context:property-placeholder location="classpath:database.properties" />
<context:component-scan base-package="com.timelee.*" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> -->
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<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>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>com.timelee.timesheet.model</value>
<value>com.timelee.users.model</value>
<value>com.timelee.*</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
Add <mvc:default-servlet-handler/> in spring-mvc-config.xmlfile. Clean the project and rebuild it. This may solve your issue.
I guess try to add in spring-mvc-config.xml. Hope this will work for you. Other things looks good.
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
Next try is add those code in the top of web.xml file. it seems different in your case.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
</web-app>
If it does not work for you then follow my link and see the difference web.xml as well as application-context.xml and dispatcher-servlet.xml
First of all i want to know that is adduser is a jap or HTML file? If yes than use simple return for it.
Second is you create adduser post method in your controller, right? Add adduser get method in controller.
Like
#requestmapping(value="adduser",requestmethod.GET)
public String adduser(){
Return // return page name
}
First, is adduser is a jap or HTML file? If HTML then use simple return for it.
Second, is your create adduser POST method in your controller? Add adduser GET method in controller.
Like:
#requestmapping(value="adduser",requestmethod.GET)
public String adduser(){
Return // return page name
}
Here, the 404 error only shows that there is no adduser.html or adduser.jsp available in your webinf folder or where you put all of your jap/HTML files.

HibernateException: No Session found for current thread

I have read and find a lot of answers on the similar questions like
org.hibernate.HibernateException: No Session found for current thread
I have tried to add tx:annotation-driven transaction-manager="transactionManager">**
but in result i had the error HTTP Status 500 - Servlet.init() for servlet mvc-dispatcher threw exception
How can i solve this problem. (Spring 3.2.0 + Hybernate 4.2.0.Final)
DetaIls.
web.xml
<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 MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
dispercher-servlet.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"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.springapp.mvc"/>
<context:annotation-config/>
<tx:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan"
value="com.springapp.mvc.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">
org.springframework.orm.hibernate4.SpringSessionContext
</prop>
<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<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/test_student" />
<property name="username" value="root" />
<property name="password" value="181987" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
HibernateSpitterDao
#Repository
public class HibernateSpitterDao {
private SessionFactory sessionFactory;
#Autowired
public HibernateSpitterDao(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory; // Конструирует DAO
}
#Transactional(readOnly = false)
public void savestudent(Student student) {
Session currentSession = sessionFactory.getCurrentSession();
Transaction transaction = currentSession.beginTransaction();
currentSession.save(student);
transaction.commit();
// Использует текущий сеанс
}
}
Controller
#Controller
#RequestMapping("/")
public class HelloController {
private HibernateSpitterDao hibernateSpitterDao;
#Autowired
public HelloController(HibernateSpitterDao hibernateSpitterDao) {
this.hibernateSpitterDao = hibernateSpitterDao;
}
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", "Hello world!");
model.addAttribute("Student",new Student());
return "hello";
}
#RequestMapping(method = RequestMethod.POST)
public String printWelcome1(#Valid Student student,
BindingResult bindingResult) {
hibernateSpitterDao.savestudent(student);
return "hello";
}
}
JSP
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<body>
<h1>${message}</h1>
<h3><strong>Start</strong></h3>
<div>
<sf:form method="post" modelAttribute="Student">
<label for="login1"> Login </label>
<sf:input path="name" id="login1" />
<p> </p>
<label for="pass"> password </label>
<sf:password path="password" id="pass" />
<p></p>
<button type="submit">Registration</button>
</sf:form>
</div>
</body>
You need to update the value you have in your dispercher-servlet.xml
Use the following value for session context.
<prop key="hibernate.current_session_context_class">thread</prop>
thread is short for org.hibernate.context.internal.ThreadLocalSessionContext
Please check this link for more detailed information.
http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#architecture-current-session
You have #Transactional annotation on your saveStudent dao method but also try and create a transaction manually in your dao method do one or other like so:
#Transactional(readOnly = false)
public void savestudent(Student student) {
Session currentSession = sessionFactory.getCurrentSession();
currentSession.save(student);
}
Also ensure that your dao class lives within or below the package that is specified in your component-scan tag otherwise the annotations will not be picked up by spring. Alternatively you could add a bean definition for your dao in the spring wiring that will also allow spring to do something with its annotations.
I had the same problem.
I was using annotation based configuration, I have configured sessionfactory, datasource and transaction manager every thing. but I did not give #EnableTransactionManagement annotation at AppConfig class.
The code looks like below after adding the transaction annotation.
#Configuration
#ComponentScan("com.bmp.*")
#EnableWebMvc
#PropertySource("classpath:${env}.properties")
#EnableTransactionManagement
public class AppConfig {
-----
}
The above annotations resolved my problem.
Solution
1. Delete Constructor in Repository class.
2. Delete transactions in Repository class.
Please use the #Repository annotation in dao layer and #Transnational on top of save student

#Autowired objects getting null value

Trying to set up a project but fail at Autowiring objects through Spring.
package se.hsr.web;
public class TestRunner {
public static void main(String[] args) {
ContactDAO cd = new ContactDAOImpl();
Contact contact = new Contact();
contact.setFirstname("Zorro");
cd.addContact(contact);
}
}
package se.hsr.web;
Running this gives me a NullPointerException when cd.addContact is invoked.
The ContactDaoImpl:
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class ContactDAOImpl implements ContactDAO {
#Autowired
private SessionFactory sessionFactory;
public void addContact(Contact contact) {
sessionFactory.getCurrentSession().save(contact);
}
My servlet file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan
base-package="se.hsr.web"/>
<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>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="contactDAOImpl"
class="se.hsr.web.ContactDAOImpl"/>
<context:annotation-config/>
</beans>
My hibernate.cfg.xml file:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="se.hsr.web.Contact" />
</session-factory>
</hibernate-configuration>
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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>HSRMVC</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>HSR</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HSR</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I suppose the error is that the SessionFactory isn't getting initialized via #Autowired correctly, but why is that? Could it be a simple directory structure/filepath problem or is it something more complicated?
Thanks in advance.
UPDATE:
ContactDAOImpl class:
#Repository
public class ContactDAOImpl extends HibernateDaoSupport implements ContactDAO{
#Autowired
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public void addContact(Contact contact) {
sessionFactory.getCurrentSession().save(contact);
}
In order to use Spring features (autowiring, call to post construct methods or aspects) you need to let Spring instanciate the instances instead of using new.
For instance:
public static void main(String[] args) {
ApplicationContext context = AnnotationConfigApplicationContext("se.hsr.web")
ContactDAO cd = (ContactDAO)context.getBean("contactDAOImpl");
Contact contact = new Contact();
contact.setFirstname("Zorro");
cd.addContact(contact);
}
AnnotationConfigApplicationContext will scan the classes in the classes in the se.hsr.web package to for classes with Spring annotations. It requires Spring 3.0 to work. Before that you should add the following line in your applicationContext.xml file:
<context:component-scan base-package="se.hsr.web" />
You need this at the top of your test class:
#RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/applicationContext.xml" and "/applicationContext-test.xml"
// in the root of the classpath
#ContextConfiguration(locations={"/applicationContext.xml", "/applicationContext-test.xml"})
public class MyTest {
I assumed JUnit4; my oversight.
You do need the context configuration tag in an application context somewhere, but I don't see anyplace in your code where you're actually opening an application context file and creating an ApplicationContext. Usually that's done in a set up method for your test. You'll have better luck if you actually create an ApplicationContext somewhere. Try reading the XML from your CLASSPATH in a setup method and see if that helps.
You need this in your Spring configuration for autowiring to work
xmlns:context="http://www.springframework.org/schema/context"
....
<context:annotation-config/>
Add #Component/#Repository to the DAO/DAOImpl.
you are creating the POJO outside of the spring context.
if you really want to be able to instanciate "manually", you can fix this, by adding <context:spring-configured /> to your configuration, and then annotating ContactDAOImpl with #Configurable
You need to retrieve the ContactDAO instance from Spring context. You are initing yourself with new keyword.
See the below link;
#Autowired annotation not able to inject bean in JUnit class
or if not unit test
ClassPathResource resource = new ClassPathResource("beans.xml");
BeanFactory factory = new XmlBeanFactory(resource);
beanFactory.getBean("nameOfYourBean");
http://static.springsource.org/spring/docs/2.0.x/reference/beans.html

Categories

Resources