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
Related
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" />
I already searching about my error but I got nothing. still error in my code so i have to post my question here.
I got an error when I run my project in eclipse with tomcat server.
I already finish the project in Spring MVC 4 + Hibernate with MongoDB. now I have to switch into Hibernate with MySQL, I am starting the project in eclipse. but when I complete the configuration of spring with hibernate its shows error.
error and structure of project are following below:
enter image description here
web.xml
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>ApplicationContext</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>DMS_MySQL</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DMS_MySQL</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/assets/*</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/pages/error/error404.jsp</location>
</error-page>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
</web-app>
SpringMVC-servlet.xml
<?xml version="1.0" encoding="UTF-8"?
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" //urls//">
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="tilesviewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
<property name="order" value="2"></property>
</bean>
<bean id="jstlviewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/pages/" />
<property name="suffix" value=".jsp" />
<property name="order" value="3"></property>
</bean>
</beans>
applicationContext.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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Enable autowire -->
<context:annotation-config />
<context:component-scan base-package="com.cs" />
<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:3306/dms" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- Session Factory Declaration -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.cs.bean" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
<prop key="hibernate.default_schema">test</prop>
<prop key="format_sql">true</prop>
<prop key="use_sql_comments">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<import resource="/WEB-INF/SpringMVC-servlet.xml"/>
</beans>
LoginController.java
package com.cs.controller;
public class LoginController {
#Autowired
private UserService userService;
#RequestMapping(value="/login")
public String execute(HttpSession session, Model model) throws Exception {
model.addAttribute("user", new UserBean());
UserBean tempUser = (UserBean) session.getAttribute("USER");
if (tempUser != null) {
return "redirect:/home";
}
return "logn";
}
#RequestMapping(value="/performLogin", method = RequestMethod.POST)
public String loginProcess(HttpSession session, Model model, #ModelAttribute("user") UserBean user,
BindingResult result) throws Exception
{
UserBean tempUser = (UserBean) session.getAttribute("USER");
if(tempUser != null)
{
return "redirect:/home";
}
if(user == null)
{
model.addAttribute("user", new UserBean());
return "login";
}
if(StringUtils.isBlank(user.getName()))
{
result.rejectValue("name", "error.required.username");
}
if(StringUtils.isBlank(user.getPassword()))
{
result.rejectValue("password", "error.required.password");
}
if(!result.hasErrors())
{
tempUser = userService.findByCredential(user);
if(tempUser != null)
{
if (tempUser.getRole().equals(RoleEnum.ADMIN)) {
session.setAttribute("USER", tempUser);
return "redirect:/home";
} else if (tempUser.getRole().equals(RoleEnum.CASHIER)) {
session.setAttribute("USER", tempUser);
return "redirect:/cHome";
}
}
else
{
result.reject("error.valid.usernamePassword");
}
}
user.setMobile("");
model.addAttribute("user", user);
return "login";
}
}
Thank you in advance.
Try http://localhost:8080/DMS_MySQL/login.
Also try changing your login controller as:
#RequestMapping(value = {"/login", "/"}, method = RequestMethod.GET)
public String execute(HttpSession session, Model model) throws Exception {
model.addAttribute("user", new UserBean());
UserBean tempUser = (UserBean) session.getAttribute("USER");
if (tempUser != null) {
return "redirect:/home";
}
return "login";//typo in your code
}
I assume you have defined mapping for login in tiles configuration.
here i find this sentence
<param-value>/WEB-INF/applicationContext.xml</param-value>
and where is your applicationContext.xml
I am building a spring + hibernate application. I'm getting a 404 error, when I run the project. The compiler does not show any error messages, it indicates that the application server (tomcat 7) loads the servlet, but does not display the root page indicated in the controller class.
Help please......
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"
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.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">
<context:property-placeholder location="classpath:resources/database.properties" />
<context:component-scan base-package="langS.com" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<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/views/" />
<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">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.langS.model.Employee</value>
<value>com.langS.EmployeeBean</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>`
Controller
#Controller
public class NewController {
#Autowired
private EmployeeService employeeService;
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String welcomeHome(){
return "index";
}
#RequestMapping(value = "/addEmployee", method = RequestMethod.GET)
public String addEmployeeRecord(){
return "addEmployee";
}
#RequestMapping(value = "/employeeList", method = RequestMethod.GET)
public String listEmployeesPage(){
return "employeesList";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<servlet>
<servlet-name>sdnext</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
404 means, that your tomcat server is getting the request, but does not now how to process the given request path.
In other words you have a bug in your URL or your configuration does not what you want it to do.
We need your configuration and desired URL to help you.
The problem is that you map the dispatcher servlet only to *.html, but you map you Controllers without using the .html suffix.
To make it work, either map you controller differently, ie :
#RequestMapping(value = "/index.html", method = RequestMethod.GET)
public String welcomeHome(){
return "index";
}
OR (and what I would do) :
Map you dispatcher servlet to all requests in web.xml :
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Then if you want to call your application with a url looking like this :
http://somehost:someport/YourApplication/
Then you'll need to map some controller method like this :
#RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
public String home() {
// your code here
}
This way, calling http://somehost:someport/YourApplication/ OR http://somehost:someport/YourApplication/index will result in the same controller method being called.
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...
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