No Hibernate Session bound to thread exception when linking it to REST - java

I am trying to link my ContactService to my ContactDao so that it can be retrieved from the database and then consumed by a REST Client but I receive the following error when running the REST Client:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:64)
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:685)
at com.aucklanduni.spring.webservices.service.ContactDaoImpl.findAll(ContactDaoImpl.java:40)
at com.aucklanduni.spring.webservices.service.ContactServiceMockImplementation.findAll(ContactServiceMockImplementation.java:56)
at com.aucklanduni.spring.webservices.restful.controller.ContactController.listData(ContactController.java:35)
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.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:685)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Here is my RestClientMain:
package com.aucklanduni.spring.webservices.restful;
import java.util.Date;
import org.joda.time.DateTime;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.web.client.RestTemplate;
import com.aucklanduni.spring.webservices.domain.Contact;
import com.aucklanduni.spring.webservices.domain.Contacts;
import com.aucklanduni.spring.webservices.service.ContactDao;
public class RestfulClientMain {
private static final String URL_GET_ALL_CONTACTS = "http://localhost:8080/Contact/contacts";
private static final String URL_GET_CONTACT_BY_ID = "http://localhost:8080/Contact/contacts/{id}";
private static final String URL_CREATE_CONTACT = "http://localhost:8080/Contact/contacts/";
private static final String URL_UPDATE_CONTACT = "http://localhost:8080/Contact/contacts/{id}";
private static final String URL_DELETE_CONTACT = "http://localhost:8080/Contact/contacts/{id}";
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:restful-client-app-context.xml");
ctx.refresh();
Contacts contacts;
Contact contact;
RestTemplate restTemplate = ctx.getBean("restTemplate", RestTemplate.class);
// Test retrieve all contacts
System.out.println("Testing retrieve all contacts:");
contacts = restTemplate.getForObject(URL_GET_ALL_CONTACTS, Contacts.class);
listContacts(contacts);
// Test retrieve contact by id
System.out.println("Testing retrieve a contact by id :");
contact = restTemplate.getForObject(URL_GET_CONTACT_BY_ID, Contact.class, 1);
System.out.println(contact);
System.out.println("");
// Test update contact
contact = restTemplate.getForObject(URL_UPDATE_CONTACT, Contact.class, 1);
contact.setFirstName("Kim Fung");
System.out.println("Testing update contact by id :");
restTemplate.put(URL_UPDATE_CONTACT, contact, 1);
System.out.println("Contact update successfully: " + contact);
System.out.println("");
// Testing delete contact
restTemplate.delete(URL_DELETE_CONTACT, 1);
System.out.println("Testing delete contact by id :");
contacts = restTemplate.getForObject(URL_GET_ALL_CONTACTS, Contacts.class);
listContacts(contacts);
// Testing create contact
System.out.println("Testing create contact :");
Contact contactNew = new Contact();
contactNew.setFirstName("JJ");
contactNew.setLastName("Gosling");
contactNew.setBirthDate(new Date());
contactNew = restTemplate.postForObject(URL_CREATE_CONTACT, contactNew, Contact.class);
System.out.println("Contact created successfully: " + contactNew);
}
private static void listContacts(Contacts contacts) {
for (Contact contact: contacts.getContacts()) {
System.out.println(contact);
}
System.out.println("");
}
}
ContactController:
package com.aucklanduni.spring.webservices.restful.controller;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import com.aucklanduni.spring.webservices.domain.Contact;
import com.aucklanduni.spring.webservices.domain.Contacts;
import com.aucklanduni.spring.webservices.service.ContactService;
#Controller
#RequestMapping(value="/contacts")
public class ContactController {
final Logger logger = LoggerFactory.getLogger(ContactController.class);
#Autowired
private ContactService contactService;
#RequestMapping(method = RequestMethod.GET)
#ResponseBody
public Contacts listData(WebRequest webRequest) {
return new Contacts(contactService.findAll());
}
#RequestMapping(value="/{id}", method=RequestMethod.GET)
#ResponseBody
public Contact findContactById(#PathVariable Long id) {
return contactService.findById(id);
}
#RequestMapping(value="/", method=RequestMethod.POST)
#ResponseBody
public Contact create(#RequestBody Contact contact, HttpServletResponse response) {
logger.info("Creating contact: " + contact);
contactService.save(contact);
logger.info("Contact created successfully with info: " + contact);
response.setHeader("Location", "/contacts/" + contact.getId());
return contact;
}
#RequestMapping(value="/{id}", method=RequestMethod.PUT)
#ResponseBody
public void update(#RequestBody Contact contact, #PathVariable Long id) {
logger.info("Updating contact: " + contact);
contactService.save(contact);
logger.info("Contact updated successfully with info: " + contact);
//return contact;
}
#RequestMapping(value="/{id}", method=RequestMethod.DELETE)
#ResponseBody
public void delete(#PathVariable Long id) {
logger.info("Deleting contact with id: " + id);
Contact contact = contactService.findById(id);
contactService.delete(contact);
logger.info("Contact deleted successfully");
}
}
ContactDaoImpl:
package com.aucklanduni.spring.webservices.service;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.aucklanduni.spring.webservices.domain.Contact;
#Component
#Repository("contactDao")
#Transactional
public class ContactDaoImpl implements ContactDao {
private Logger _logger = LoggerFactory.getLogger(ContactDaoImpl.class);
private SessionFactory _sessionFactory;
public SessionFactory getSessionFactory() {
return _sessionFactory;
}
#Resource
public void setSessionFactory(SessionFactory sessionFactory) {
this._sessionFactory = sessionFactory;
_logger.debug("SessionFactory class: " + sessionFactory.getClass().getName());
}
#Transactional(readOnly=true)
public List<Contact> findAll() {
List<Contact> result = _sessionFactory.getCurrentSession().createQuery("from Contact c").list();
return result;
}
public List<Contact> findAllWithDetail() {
return _sessionFactory.getCurrentSession().getNamedQuery("Contact.findAllWithDetail").list();
}
public Contact findById(Long id) {
return (Contact) _sessionFactory.getCurrentSession().
getNamedQuery("Contact.findById").setParameter("id", id).uniqueResult();
}
public Contact save(Contact contact) {
_sessionFactory.getCurrentSession().saveOrUpdate(contact);
_logger.info("Contact saved with id: " + contact.getId());
return contact;
}
public void delete(Contact contact) {
_sessionFactory.getCurrentSession().delete(contact);
_logger.info("Contact deleted with id: " + contact.getId());
}
}
ContactServiceImpl (ignore comments as they were used for mock testing purposes):
package com.aucklanduni.spring.webservices.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.aucklanduni.spring.webservices.domain.Contact;
import com.aucklanduni.spring.webservices.domain.Contacts;
#Component
#Service("contactService")
public class ContactServiceMockImplementation implements ContactService {
//private Contacts _contacts;
#Autowired
private ContactDao contactDao;
// public ContactServiceMockImplementation() {
// Contact contact1 = new Contact();
// contact1.setId(1L);
// contact1.setVersion(1);
// contact1.setFirstName("Clint");
// contact1.setLastName("Eastwood");
// contact1.setBirthDate(new Date());
//
// Contact contact2 = new Contact();
// contact2.setId(1L);
// contact2.setVersion(1);
// contact2.setFirstName("Robert");
// contact2.setLastName("Redford");
// contact2.setBirthDate(new Date());
//
// Contact contact3 = new Contact();
// contact3.setId(1L);
// contact3.setVersion(1);
// contact3.setFirstName("Michael");
// contact3.setLastName("Caine");
// contact3.setBirthDate(new Date());
//
// List<Contact> contactList = new ArrayList<Contact>();
// contactList.add(contact1);
// contactList.add(contact2);
// contactList.add(contact3);
//
// _contacts = new Contacts(contactList);
// }
#Override
public List<Contact> findAll() {
//return _contacts.getContacts();
return contactDao.findAll();
}
// #Override
// public List<Contact> findByFirstName(String firstName) {
// List<Contact> results = new ArrayList<Contact>();
//
// for(Contact contact : _contacts.getContacts()) {
// if(contact.getFirstName().equals(firstName)) {
// results.add(contact);
// }
// }
// return results;
// }
#Override
public Contact findById(Long id) {
// Contact result = null;
//
// for(Contact contact : _contacts.getContacts()) {
// if(contact.getId() == id) {
// result = contact;
// break;
// }
// }
// return result;
return contactDao.findById(id);
}
#Override
public Contact save(Contact contact) {
//return contact;
return contactDao.save(contact);
}
#Override
public void delete(Contact contact) {
// TODO Auto-generated method stub
contactDao.delete(contact);
}
}
Here is my restful-client-app-context.xml which includes the Hibernate 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" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<jdbc:embedded-database id="dataSource" type="H2">
<jdbc:script location="classpath:schema.sql"/>
<jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="springSessionFactory"/>
</bean>
<!-- <bean id="contactDao" class="com.aucklanduni.spring.webservices.service.ContactDao"></bean> -->
<tx:annotation-driven/>
<context:component-scan base-package="com.aucklanduni.spring.webservices.service" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="springSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.aucklanduni.spring.webservices.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<!-- <constructor-arg ref="httpRequestFactory"/>-->
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="castorMarshaller"/>
<property name="unmarshaller" ref="castorMarshaller"/>
<property name="supportedMediaTypes">
<list>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="application"/>
<constructor-arg index="1" value="xml"/>
</bean>
</list>
</property>
</bean>
</list>
</property>
</bean>
<bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller">
<property name="mappingLocation" value="classpath:oxm-mapping.xml"/>
</bean>
</beans>

Related

Transaction rollback not working when rollback is done on MySql db

I have implemented transactional rollback in the following way. This code worked well when I tried to implement the same on HSql DB and SQL Server. But the same transactional rollback is not working when implemented on MySQL DB. What could be the possible solution for rolling back the transaction in case of MySQL?
Here is my code -
xml file-> implement.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<!-- Initialization for data source -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://(mydb details)"/>
<property name="username" value="(my db username)"/>
<property name="password" value="(my db password)"/>
</bean>
<!-- Initialization for TransactionManager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Definition for studentJDBCTemplate bean -->
<bean id="implementOnlyTransactions" class="Transactions.implementOnlyTransactions">
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
</bean>
</beans>
implementOnlyTransactions.java->
package Transactions;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
public class implementOnlyTransactions {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
private PlatformTransactionManager transactionManager;
public void setDataSource(DataSource dataSource) throws SQLException {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void create(Integer id, String name) throws Exception {
TransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(def);
try {
String SQL1 = "insert into Student (ID,Name) values (?, ?)";
int r = jdbcTemplateObject.update(SQL1, id, name);
System.out.println("Inserted Name = " + name + ", ID = " + id);
if(r>0){
transactionManager.rollback(status);
}
transactionManager.commit(status);
} catch (DataAccessException e) {
System.out.println("Error in creating record, rolling back");
//transactionManager.rollback(status);
throw e;
}
}
}
MainClass.java -->
package Transactions;
import java.sql.SQLException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainClass {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("xmlFiles/implement.xml");
implementOnlyTransactions implemt =
(implementOnlyTransactions)context.getBean("implementOnlyTransactions");
try {
implemt.create(36,"bye2");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

C3P0 connection pooling not working in spring mvc (maven project)

This is the applicationContext.xml file which i placed in the src/main/resources folder.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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:jdbc.properties"/>
<!-- Employee DB data source. -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="minPoolSize" value="${jdbc.minPoolSize}" />
<property name="maxStatements" value="${jdbc.maxStatements}" />
<property name="testConnectionOnCheckout" value="${jdbc.testConnection}" />
</bean>
<bean id="Utilities" class="com.pooling.test.Utilities">
</bean>
<context:component-scan base-package="com.pooling.controllers">
</context:component-scan>
This is the jdbc.properties file which i placed in the src/main/resources folder.
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/books
jdbc.username=root
jdbc.password=admin
jdbc.maxPoolSize=50
jdbc.minPoolSize=10
jdbc.maxStatements=10
jdbc.testConnection=true
jdbc.unreturnedConnectionTimeout=240
jdbc.debugUnreturnedConnectionStackTraces=true
This is the Utilities class that contains the logic that i wish to perform
package com.pooling.test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import com.jolbox.bonecp.BoneCP;
public class Utilities {
private final String CLASS_NAME = "Utilities";
#Autowired
private DataSource datasource;
public String createListofCategories()
{
String METHOD_NAME = "createListofCategories()";
/*//===========================================================================
TransactionDefinition mDefinition = new DefaultTransactionDefinition();
TransactionStatus mStatus = mTransactionManager.getTransaction(mDefinition);
//=========================================================================== */
String listOfCategories = "";
String sequel = "select distinct category_id, key_desc from book_resource_view, keywords_record_table";
sequel = sequel + " where keyword_key=category_id and category_id > 1 ";
sequel = sequel + " order by key_desc";
Connection connection = null;
ResultSet results = null;
Statement state = null;
int categoryID = 0;
String categoryDesc = "";
int numRows = 0;
try
{
connection = datasource.getConnection();
state = connection.createStatement();
results = state.executeQuery(sequel);
results.last();
numRows = results.getRow();
//======================================
results.beforeFirst();
for(int i=0; results.next(); i++){
listOfCategories = listOfCategories + "<td><ul id=\"category_list\">";
for(int j=0; j<16; j++){
categoryID = results.getInt("category_id");
categoryDesc = results.getString("key_desc");
listOfCategories = listOfCategories + "<li>"+categoryDesc+"</li>";
if(!results.next()){
break;
}
}
results.previous();
listOfCategories = listOfCategories + "</ul></td>";
}
listOfCategories = "<tr>"+listOfCategories+"</tr>";
}
catch (SQLException localSQLException)
{
try
{
results.close();
state.close();
connection.close();
}
catch (SQLException localSQLException1)
{
}
}
finally
{
try {
results.close();
state.close();
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return listOfCategories;
}
This is the controller code that i wish to call from the browser.
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.pooling.test.ConnectionManager;
import com.pooling.test.Utilities;
#Controller
public class TestController {
#RequestMapping(value="/testing",method=RequestMethod.GET)
public #ResponseBody String getCategories(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Utilities utilities = (Utilities) context.getBean("Utilities");
return utilities.createListofCategories();
}
}
PROBLEM: the problem is that the pool gets initialized properly but when i keep executing the same controller request again and again the connection pool keeps on creating connections until the server gives "too many connections" error
I think the problem lies in the fact that you create a new ApplicationContext everytime the getCategories() method is called.
As #Chrylis already mentioned, you don't need to call context.getBean().
Replace the two lines from ApplicationContext to context.getBean() to #Autowired Utilities utilities. Just like you did with datasource in your Utilities class.

http status 500 spring webservice hibernate

I'm getting an status http 500, it says the server encountered an internal error that prevented it from fulfilling this request. But the apache log shows no errors at all.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.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 -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="org.postgresql.Driver"/>
<beans:property name="url" value="jdbc:postgresql://localhost:5432/tms"/>
<beans:property name="username" value="postgres"/>
<beans:property name="password" value="paswoord"/>
</beans:bean>
<beans:bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="configLocation">
<beans:value>classpath:hibernate.cfg.xml</beans:value>
</beans:property>
<beans:property name="configurationClass">
<beans:value>org.hibernate.cfg.AnnotationConfiguration</beans:value>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">${jdbc.dialect}</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<tx:annotation-driven />
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>
<context:component-scan base-package="be.pxl.publictms" />
</beans:beans>
testController the getUsers method works partly i can print the results but it won't return it as an populated list.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import be.pxl.publictms.model.Computer;
import be.pxl.publictms.pojo.Gebruiker;
import be.pxl.publictms.service.GebruikerService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
#Controller
#RequestMapping("test")
public class TestController {
#Autowired
private GebruikerService gebruikerService;
#RequestMapping(value = "pc",method = RequestMethod.GET)
public #ResponseBody Computer testMethod() {
return new Computer(0, "DELL");
}
#RequestMapping(value = "users",method = RequestMethod.GET)
public #ResponseBody List<Gebruiker> getUsers(){
List<Gebruiker> users = gebruikerService.getGebruikers();
System.out.println("***********************************************");
for(Gebruiker user: users){
System.out.println(user.toString());
}
System.out.println("***********************************************");
/*List<Gebruiker> users = new ArrayList<Gebruiker>();
users.add(new Gebruiker(1, "laurens", "test"));
users.add(new Gebruiker(2, "laurens", "test"));
users.add(new Gebruiker(3, "laurens", "test"));*/
return users;
}
}
GebruikerService:
import be.pxl.publictms.DAO.GebruikerDAO;
import be.pxl.publictms.pojo.Gebruiker;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
*
* #author 11302785
*/
#Service
public class GebruikerServiceImpl implements GebruikerService{
#Autowired
private GebruikerDAO gebruikerDao;
#Transactional
public void addGebruiker(Gebruiker gebruiker) {
gebruikerDao.addGebruiker(gebruiker);
}
#Transactional
public List<Gebruiker> getGebruikers() {
return gebruikerDao.getGebruikers();
}
#Transactional
public void deleteGebruiker(int id) {
gebruikerDao.deleteGebruiker(id);
}
#Transactional
public void updateGebruiker(Gebruiker gebruiker) {
gebruikerDao.updateGebruiker(gebruiker);
}
}
gebruikerDAO:
import be.pxl.publictms.pojo.Gebruiker;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
/**
*
* #author 11302785
*/
#Repository
public class GebruikerDAOImpl implements GebruikerDAO{
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void addGebruiker(Gebruiker gebruiker) {
sessionFactory.getCurrentSession().save(gebruiker);
}
#Override
public List<Gebruiker> getGebruikers() {
return sessionFactory.getCurrentSession().createQuery("from Gebruiker").list();
}
#Override
public void deleteGebruiker(int id) {
Gebruiker gebruiker = (Gebruiker)sessionFactory.getCurrentSession().load(Gebruiker.class, id);
if(null != gebruiker){
sessionFactory.getCurrentSession().delete(gebruiker);
}
}
#Override
public void updateGebruiker(Gebruiker gebruiker) {
sessionFactory.getCurrentSession().update(gebruiker);
}
}
pojo class gebruiker (it's dutch, it meaning is User... sorry for the dutch parts in it):
import java.util.HashSet;
import java.util.Set;
/**
* Gebruiker generated by hbm2java
*/
public class Gebruiker implements java.io.Serializable {
private int gebruikerid;
private Werknemer werknemer;
private String gebruikersnaam;
private String paswoord;
private Set<Bericht> berichtsForGebruikerid = new HashSet<Bericht>(0);
private Set<Bericht> berichtsForOntvangerid = new HashSet<Bericht>(0);
public Gebruiker() {
}
public Gebruiker(int gebruikerid, String gebruikersnaam, String paswoord) {
this.gebruikerid = gebruikerid;
this.gebruikersnaam = gebruikersnaam;
this.paswoord = paswoord;
}
public Gebruiker(int gebruikerid, Werknemer werknemer, String gebruikersnaam, String paswoord, Set<Bericht> berichtsForGebruikerid, Set<Bericht> berichtsForOntvangerid) {
this.gebruikerid = gebruikerid;
this.werknemer = werknemer;
this.gebruikersnaam = gebruikersnaam;
this.paswoord = paswoord;
this.berichtsForGebruikerid = berichtsForGebruikerid;
this.berichtsForOntvangerid = berichtsForOntvangerid;
}
public int getGebruikerid() {
return this.gebruikerid;
}
public void setGebruikerid(int gebruikerid) {
this.gebruikerid = gebruikerid;
}
public Werknemer getWerknemer() {
return this.werknemer;
}
public void setWerknemer(Werknemer werknemer) {
this.werknemer = werknemer;
}
public String getGebruikersnaam() {
return this.gebruikersnaam;
}
public void setGebruikersnaam(String gebruikersnaam) {
this.gebruikersnaam = gebruikersnaam;
}
public String getPaswoord() {
return this.paswoord;
}
public void setPaswoord(String paswoord) {
this.paswoord = paswoord;
}
public Set<Bericht> getBerichtsForGebruikerid() {
return this.berichtsForGebruikerid;
}
public void setBerichtsForGebruikerid(Set<Bericht> berichtsForGebruikerid) {
this.berichtsForGebruikerid = berichtsForGebruikerid;
}
public Set<Bericht> getBerichtsForOntvangerid() {
return this.berichtsForOntvangerid;
}
public void setBerichtsForOntvangerid(Set<Bericht> berichtsForOntvangerid) {
this.berichtsForOntvangerid = berichtsForOntvangerid;
}
#Override
public String toString(){
return this.gebruikersnaam + " " + this.paswoord;
}
}

Xstream marshaller not unmarshelling xml post body

I am trying to create a spring rest service. My servlet.xml is like following:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/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">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<!-- Database Configuration -->
<import resource="classpath:DataSource.xml"/>
<import resource="classpath:Hibernate.xml"/>
<!-- Beans Declaration -->
<import resource="classpath:Employee.xml"/>
<context:component-scan base-package="com.nilenium.service.controller" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter"/>
<ref bean="marshallingHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true"/>
<property name="annotatedClasses">
<list>
<value>com.nilenium.employee.model.Employee</value>
<value>com.nilenium.employee.model.EmployeeRecord</value>
</list>
</property>
</bean>
<bean id="marshallingHttpMessageConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="xstreamMarshaller"/>
<property name="unmarshaller" ref="xstreamMarshaller"/>
</bean>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="ignoreAcceptHeader" value="true" />
<property name="defaultContentType" value="application/json" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<!-- XML View -->
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true"/>
<property name="aliases">
<props>
<prop key="employee">com.nilenium.employee.model.Employee</prop>
<prop key="employee">com.nilenium.employee.model.EmployeeRecord</prop>
</props>
</property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
</beans>
And my model class is like this:
package com.nilenium.employee.model;
import java.io.Serializable;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonRootName;
import com.thoughtworks.xstream.annotations.XStreamAlias;
#XStreamAlias("employee")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private int employeeId;
private String employeeName;
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public Employee(int employeeId, String employeeName)
{
this.employeeId = employeeId;
this.employeeName = employeeName;
}
public Employee() {
}
}
My service controller class is like this:
package com.nilenium.service.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import com.nilenium.employee.bo.EmployeeBo;
import com.nilenium.employee.model.Employee;
import com.nilenium.employee.model.EmployeeRecord;
#Controller
#RequestMapping("/Service")
public class NileniumServiceController {
#Autowired
private EmployeeBo employeeBo;
#ExceptionHandler
public String exceptionHandler(Exception e){
return "serviceError";
}
#RequestMapping(value = "employeeId/{employeeId}", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public Employee getEmployeeName(#PathVariable int employeeId,
HttpServletResponse resp,
ModelMap model) {
// System.out.println("Emp Name : " + employeeName);
Employee empReturned = new Employee();
empReturned.setEmployeeId(employeeId);
empReturned.setEmployeeName("Demo Name");
return empReturned;
}
#RequestMapping(value = "/employees", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public EmployeeRecord getAllEmployeeDetails(HttpServletResponse resp,
ModelMap model) {
List<Employee> empListReturned = employeeBo.getAllEmployee();
EmployeeRecord eRecords = new EmployeeRecord();
eRecords.setEmployeeList(empListReturned);
return eRecords;
}
#RequestMapping(value = "/storeemployee",method = RequestMethod.POST, headers = {"Accept=text/xml, application/json"})
public Employee storeEmpRecord(#RequestBody Employee employee,HttpServletResponse resp,
ModelMap model)
{
System.out.println("Emp Id received : "+employee.getEmployeeId());
System.out.println("Emp Name received : "+employee.getEmployeeName());
// Employee empReturned = employeeBo.findByEmployeeId(1);
return employee;
}
}
When I am trying to post an xml to the storeEmpRecord method xstream marshaller is not able to convert the xml request to respective object (Employee object).
My test client is like this:
package com.nilenium.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.aop.framework.adapter.DefaultAdvisorAdapterRegistry;
import com.nilenium.employee.model.Employee;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class RestPostTest {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setEmployeeId(1);
emp.setEmployeeName("Nilalohita");
XStream xStream = new XStream(new DomDriver());
xStream.alias("employee", Employee.class);
System.out.println(xStream.toXML(emp));
String xmlBody = xStream.toXML(emp);
HttpClient client = new DefaultHttpClient();
String jsonDemo = "{\"employeeId\":2,\"employeeName\":\"He-Man\"}";
try {
HttpPost post = new HttpPost("http://localhost:8080/SampleMaven/Service/storeemployee");
// post.addHeader("Accept", "application/json");
// post.addHeader("Content-Type", "application/json");
post.addHeader("Accept", "application/xml");
post.addHeader("Content-Type", "application/xml");
StringEntity entity = new StringEntity(xmlBody, "UTF-8");
// entity.setContentType("application/json");
entity.setContentType("application/xml");
post.setEntity(entity);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please let me know if i am doing something wrong. The same thing is working for jaxb using #XMLroot for Employee class instead of #XStreamAlias("employee").
I am getting the following error. the full stack trace is like this
Caused by:</h3><pre>javax.servlet.ServletException: Unable to locate object to be marshalled in model: {}
at org.springframework.web.servlet.view.xml.MarshallingView.renderMergedOutputModel(MarshallingView.java:100)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206)
at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:648)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:205)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
The problem is in the controller method :
#RequestMapping(value = "/storeemployee",method = RequestMethod.POST, headers = {"Accept=text/xml, application/json"})
public Employee storeEmpRecord(#RequestBody Employee employee,HttpServletResponse resp,
ModelMap model)
{
System.out.println("Emp Id received : "+employee.getEmployeeId());
System.out.println("Emp Name received : "+employee.getEmployeeName());
// Employee empReturned = employeeBo.findByEmployeeId(1);
return employee;
}
Spring MVC does not (cannot) add objects to model automatically. You need to add the employee object to the ModelMap. The model map is then passed to the marshaling view, which looks for any objects that it can marshal, and marshals them to response.
Unable to locate object to be marshalled in model: {} Means the Marshalling View received a ModelMap with no objects that have the XStream annotations.
Hope this helps.

Database connection spring framework unresolved

i had earlier created the spring framework, then replaced with the database connection, but there is problem in creating the beans.
also receiving the below error during the deployment.
DEFAULT=C:\Users\gopc\Documents\NetBeansProjects\HelloSpringJDBC\build\web&name=HelloSpringJDBC&contextroot=/HelloSpringJDBC&force=true
failed on GlassFish Server 3.1.2 Error occurred during deployment:
Exception while loading the app : java.lang.IllegalStateException:
ContainerBase.addChild: start: org.apache.catalina.LifecycleException:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'productManager' defined in ServletContext
resource [/WEB-INF/applicationContext.xml]: Error setting property
values; nested exception is
org.springframework.beans.NotWritablePropertyException: Invalid
property 'productDao' of bean class [SimpleProductManager]: Bean
property 'productDao' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the
getter?. Please see server.log for more details.
C:\Users\gopc\Documents\NetBeansProjects\HelloSpringJDBC\nbproject\build-impl.xml:1029:
The module has not been deployed. See the server log for details.
Source
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="externalDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" scope="singleton" destroy-method="close">
<property name="driverClassName" value="sun.jdbc.odbc.JdbcOdbcDriver"/>
<property name="url" value="jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ=C://Users//gopc//Documents//odbc_sql.accdb"/>
<property name="username" value=""/>
<property name="password" value=""/>
</bean>
<bean id="productManager" class="SimpleProductManager">
<property name="productDao" ref="productDao"/>
</bean>
<bean id="productDao" class="JdbcProductDao">
<property name="dataSource" ref="externalDataSource"/>
</bean>
</beans>
spirngapp-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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<bean name="/hello.htm" class="HelloController">
<property name="productManager" ref="productManager"/>
</bean>
<!-- we can prefix="/"
http://localhost:8080/HelloSpring/hello.htm
specify the path in modelview from the controller
OR
Decouple the view from the controller
prefix="/WEB-INF/jsp/"
-->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en_US"/>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
</beans>
JdbcProductDao.java
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
public class JdbcProductDao extends SimpleJdbcDaoSupport implements ProductDao {
protected final Log logger = LogFactory.getLog(getClass());
public List<Product> getProductList() {
logger.info("Getting products!");
List<Product> products = getSimpleJdbcTemplate().query(
"select id, description, price from products",
new ProductMapper());
return products;
}
public void saveProduct(Product prod) {
logger.info("Saving product: " + prod.getDescription());
int count = getSimpleJdbcTemplate().update(
"update products set description = :description, price = :price where id = :id",
new MapSqlParameterSource().addValue("description", prod.getDescription())
.addValue("price", prod.getPrice())
.addValue("id", prod.getId()));
logger.info("Rows affected: " + count);
}
private static class ProductMapper implements ParameterizedRowMapper<Product> {
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
Product prod = new Product();
prod.setId(rs.getInt("id"));
prod.setDescription(rs.getString("description"));
prod.setPrice(new Double(rs.getDouble("price")));
return prod;
}
}
}
SimpleProductManager.java
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class SimpleProductManager implements ProductManager {
protected final Log logger = LogFactory.getLog(getClass());
private ProductDao productDao;
public List<Product> getProductDao() {
//throw new UnsupportedOperationException();
return productDao.getProductList();
}
public void increasePrice(int percentage) {
//throw new UnsupportedOperationException();
List <Product> products = productDao.getProductList();
for (Product product : products) {
double newPrice = product.getPrice() * (100 + percentage)/100;
product.setPrice(newPrice);
productDao.saveProduct(product);
}
}
public void setProductDao(ProductDao productDao) {
//throw new UnsupportedOperationException();
logger.info("inside the setProducts in SimpleProductManager");
this.productDao = productDao;
}
}
HelloController.java
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
public class HelloController implements Controller {
private ProductManager productManager;
protected final Log logger = LogFactory.getLog(getClass());
/*
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
logger.info("Returning hello view");
String now = ( new Date().toString());
logger.info("time now:"+ now);
//return new ModelAndView("hello");
//return new ModelAndView("WEB-INF/jsp/hello","now",now);
//decouple the view from the controller
return new ModelAndView("hello","now",now);
}
*/
//Writing some business logic in the controller
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String now = (new java.util.Date()).toString();
logger.info("returning hello view with " + now);
Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("now", now);
myModel.put("products", this.productManager.getProductDao());
return new ModelAndView("hello", "model", myModel);
}
public void setProductManager(ProductManager productManager)
{
this.productManager = productManager;
}
}
hey the problem got resovled, after i had modified, the following..
1) applicationContext with mapping for the bean "productManager" with ref productDao.
2) ProductManager interface with new method call getProducts(), then implemenent in the SimpleProductManager and which call the ProductDao.getProducts(), where the sql query is being defined.

Categories

Resources