How to insert into HSQL from a thymeleaf form - java

Controller
package com.hellokoding.hello.web;
import com.hellokoding.hello.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.hellokoding.hello.dao.*;
#Controller
public class HelloController {
#Autowired
StudentDAO studentDao;
#RequestMapping("/")
public String index() {
return "input";
}
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(#RequestParam(value = "name", required = false, defaultValue = "World") String name,
Model model) {
model.addAttribute("name", name);
return "hello";
}
#RequestMapping(value = "/studentRegister", params = {"save"})
public String saveSeedstarter(final Student student, final BindingResult bindingResult, final ModelMap model) {
if (bindingResult.hasErrors()) {
return "input";
}
model.addAttribute("student", student);
studentDao.saveStudent(student);
return "result";
}
#ModelAttribute("student")
public Student getStudent(){
return new Student();
}
/*
* #RequestMapping(value = "/studentRegister", method = RequestMethod.POST)
* public String index(#RequestParam(value="save") Student student, Model
* model) { model.addAttribute("student", student); return "hello"; }
*/
}
Hsql db in
The url is jdbc:hsqldb:mem:mydb
I dunno where the db files will be??. If i open in database manager then i cannot see the student database. Help me to fix this
I have the form
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Thyme Seed Starter Manager</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h2>Add new student</h2>
<form action="#" th:action="#{/studentRegister}"
th:object="${student}" method="post">
<input type="text" th:field="*{firstName}"/>
<input type="text" th:field="*{lastName}"/>
<input type="submit" name="save" value="save"/>
</form>
</body>
</html>
Web.xml
<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_2_5.xsd"
version="2.5">
<display-name>Hello Spring MVC</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appconfig-root.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
appconfig-root.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="appconfig-mvc.xml"/>
<!-- Scans within the base package of the application for #Component classes to configure as beans -->
<context:component-scan base-package="com.hellokoding.hello.*"/>
<context:property-placeholder location="classpath:application.properties"/>
</beans>
appconfig-mvc.xml
<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="http://www.springframework.org/schema/beans"
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">
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="templateResolver"
class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>WEB-INF/configuration.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>${jdbc.driver.className}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="packagesToScan" value="com.hellokoding.hello.pojo" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<tx:annotation-driven />
</beans>
I need to submit the form i have added the it to student model attribute in controller. I need to insert this data into student db of HSQL. How to proceed with modifications in spring xml.
I have included a persistence.xml under resources/META-INF
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
<persistence-unit name="manager" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.hellokoding.hello</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:mydb"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
configuration.properties
jdbc.driver.className=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:mem:mydb
jdbc.username=sa
jdbc.password=
jdbc.hibernate.dialect=org.hibernate.dialect.HSQLDialect
DAO interface
package com.hellokoding.hello.dao;
import java.util.List;
import com.hellokoding.hello.pojo.Student;
public interface StudentDAO {
public void saveStudent(Student student);
public List<Student> getAllStudents(Student student);
public Student getStudentById(String studentId);
public void deleteStudent(Student student);
}
DAO implementation
package com.hellokoding.hello.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.hellokoding.hello.pojo.Student;
//This will make easier to autowired
#Repository("StudentDAO")
#Transactional
public class StudentDAOImpl implements StudentDAO {
private HibernateTemplate hibernateTemplate;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#Transactional(readOnly = false)
public void saveStudent(Student student) {
System.out.println("Inside");
hibernateTemplate.saveOrUpdate(student);
}
#Transactional(readOnly = false)
public void deleteStudent(Student student) {
hibernateTemplate.delete(student);
}
#SuppressWarnings("unchecked")
public List<Student> getAllStudents(Student student) {
return (List<Student>) hibernateTemplate.find("from " + Student.class.getName());
}
public Student getStudentById(String studentId) {
return hibernateTemplate.get(Student.class, studentId);
}
}
I have tried with hibernate and i was trying to insert into the db.
Student Bean
package com.hellokoding.hello.pojo;
import javax.persistence.*;
import java.io.Serializable;
//import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name = "student_table")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
public static long getSerialversionuid() {
return serialVersionUID;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "first_name", nullable = false)
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "last_name", nullable = false)
private String lastName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Student(){
}
public Student(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
}
The id is also not generating and its not inserting the HSQL db table called student_table
Pom.xml
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hellokoding</groupId>
<artifactId>hello</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Hello Spring MVC</name>
<url>http://maven.apache.org</url>
<properties>
<jdk.version>1.8</jdk.version>
<spring.version>4.1.6.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
<junit.version>3.8.1</junit.version>
<logback.version>1.1.3</logback.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>${thymeleaf.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>1.8.0.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.5.Final</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.8.5.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<!-- embedded Jetty server, for testing -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.11.v20150529</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webApp>
<contextPath>/</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
</build>
</project>

Related

Error creating bean with name 'org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping

I am trying to fix below error:
Error creating bean with name 'org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping'
but still getting following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.web.servlet.handler.AbstractHandlerMapping.obtainApplicationContext()Lorg/springframework/context/ApplicationContext;
Below is my setup:
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:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.javatpoint"/>
<import resource="classpath:IOC.xml"/>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_3_0.xsd"
version="3.0">
<display-name>Bai Tap</display-name>
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
IOC.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:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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-4.3.xsd">
<bean id="ds" 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/BaiTap" />
<property name="username" value="root" />
<property name="password" value="1234" />
</bean>
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.javatpoint.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
Employee.java
package com.javatpoint;
public class Employee {
private int id;
private String name;
private float salary;
public Employee(int id, String name, float salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
EmployeeDao.java
package com.javatpoint;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int saveEmployee(Employee e) {
String query = "insert into employee(id,name,salary) values(" + e.getId() +"," + e.getName() + "," + e.getSalary() +")";
return jdbcTemplate.update(query);
}
public int updateEmployee(Employee e) {
String query = "update employee set name = "+e.getName()+",salary="+e.getSalary()+"where id="+e.getId()+"";
return jdbcTemplate.update(query);
}
public int deleteEmployee(Employee e) {
String query = "delete from employee where id = "+e.getId()+"";
return jdbcTemplate.update(query);
}
}
Test.java
package com.javatpoint;
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.ResponseBody;
#Controller
public class Test {
#RequestMapping("/")
#ResponseBody
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("IOC.xml");
EmployeeDao dao = (EmployeeDao) context.getBean("edao");
int status = dao.saveEmployee(new Employee(102,"Amit",3500));
System.out.println(status);
}
}
porm.xml http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.javatpoint
BaiTap
0.0.1-SNAPSHOT
war
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aspectj/aspectjrt -->
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
</dependencies>
</project>
your code
#Controller
public class Test {
#RequestMapping("/")
#ResponseBody
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("IOC.xml");
EmployeeDao dao = (EmployeeDao) context.getBean("edao");
int status = dao.saveEmployee(new Employee(102,"Amit",3500));
System.out.println(status);
}
}
return type is void, it means the method return nothing. Therefore, it cannot return #ResponseBody in same time.
main method is reserved for entry point of Java Class, you must change method's name.
How have you constructed your project?
The java.lang.NoSuchMethodError means that this method does not exist at runtime.
This method would have been invoked from inside a library but it was unable to find that method.
If it is a non Spring Boot project, can you please check if you have included spring-core and spring-context in your setup.
As you have applicationContext.xml which imports IOC.xml you should change your
ApplicationContext context = new ClassPathXmlApplicationContext("IOC.xml");
to
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
EDIT
You need to restructure your controller class also
package com.javatpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("IOC.xml");
EmployeeDao dao = (EmployeeDao) context.getBean("edao");
int status = dao.saveEmployee(new Employee(102,"Amit",3500));
System.out.println(status);
}
}
And finally run your this class.

Spring + Hibernate, can not read xml error

I am a newbie in Spring + Hibernate, but I have worked on this problem for last one day. I still can not figure out what is the root cause, and what should I do. So, thank you in advance if any one can give me some advice.
Here is a problem, I just write a simple test class, but when I ran, there is an exception:
??: Exception encountered during context initialization - cancelling refresh >attempt: org.springframework.beans.factory.BeanCreationException: Error >creating bean with name 'sessionFactory' defined in class path resource >>>>>>>[ApplicationContext.xml]: Invocation of init method failed; nested exception is >org.hibernate.InvalidMappingException: Unable to read XML
Exception in thread "main" >org.springframework.beans.factory.BeanCreationException: Error creating bean >with name 'sessionFactory' defined in class path resource >[ApplicationContext.xml]: Invocation of init method failed; nested exception is> org.hibernate.InvalidMappingException: Unable to read XML
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.xw.test.Test.main(Test.java:30)
And here is the class source code:
package com.domain;
import java.util.Date;
public class Employee {
private Integer id;
private String name;
private String email;
private java.util.Date hiredate;
private Float salary;
public Float getSalary() {
return salary;
}
public void setSalary(Float salary) {
this.salary = salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public java.util.Date getHiredate() {
return hiredate;
}
public void setHiredate(java.util.Date hiredate) {
this.hiredate = hiredate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Employee( String name, String email, Date hiredate,
Float salary) {
this.name = name;
this.email = email;
this.hiredate = hiredate;
this.salary = salary;
}
public Employee(){
}
}
And here is the Employee.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-mapping package="com.domain">
<class name="Employee" table="employee">
<id name="id" type="java.lang.Integer">
<generator class="native" ></generator>
</id>
<property name="email" type="java.lang.String" >
<column name="email" length="64"/>
</property>
<property name="hiredate" type="java.util.Date">
<column name="hiredate" />
</property>
<property name="name" type="java.lang.String">
<column name="name"/>
</property>
<property name="salary" type="java.lang.Float">
<column name="salary"/>
</property>
</class>
</hibernate-mapping>
And here is the ApplicationContext.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<bean id="testService" class="com.xw.test.TestService">
<property name="name" value="XingWang"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#127.0.0.1:1521:orcl"/>
<property name="username" value="scott"/>
<property name="password" value="111111"/>
<property name="initialSize" value="3"/>
<property name="maxActive" value="500"/>
<property name="maxIdle" value="2"/>
<property name="minIdle" value="1"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>com/domain/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.OracleDialect
</value>
</property>
</bean>
</beans>
And the pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>myssh</groupId>
<artifactId>myssh</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebRoot</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.2.Final</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
</dependencies>
And here is the smiple test class source code:
/**
*
*/
package com.xw.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.domain.Employee;
/**
* #author Administrator
*
*/
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");
SessionFactory sf = (SessionFactory) ac.getBean("sessionFactory");
Session s = sf.openSession();
Employee employee = new Employee( "aa", "aa.sohu#com", new java.util.Date(),
(float) 234.56) ;
Transaction tx = s.beginTransaction();
s.save(employee);
tx.commit();
}
}
Thank you so much for any advice!
The properties should be declared like below inside your sessionFactory Bean.
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
</props>
so your sessionFactory bean would be like below.
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>com/domain/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
</props>
</property>
sometimes there is a chance of cant pick ur config files because of compiler dont konw which file shoul it take for configuration.so for this reason u should explicitly import those config file via 2 methods as i know
1)by using class
#Configuration
#ImportResource(value = {"classpath:{filename-within-resource}/Employee.hbm.xml"},"classpath:{filename-within-resource}/ApplicationContext.cfg.xml")
public class CommonSolutionConfig {
}
2)by using xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<import resource="classpath:{filename-within-resource}/Employee.hbm.xml"/>
<import resource="classpath:{filename-within-resource}/ApplicationContext.cfg.xml"/>
</beans>
hopefully it will solve ur problem

Spring + Hibernate + Maven org.hibernate.MappingException: AnnotationConfiguration instance is required

I am new to Spring so as to Hibernate frameworks. The task is to create a project with both front and back ends, but for now I would like to focus on DB connection.
I have MySQL database on localhost within my MySQL server. There is a simple application which needs to create clients, orders and search for them in the DB, so the task is trivial. Yet, I encounter the following ecxeption:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory ee.st.running.dao.ClientDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [config.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="ee.st.running.model.Client"/>
I tried some manipulations, read many similar issues here, which led me to other exceptions much like this.
My config.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package=".*" />
<tx:annotation-driven/>
<context:annotation-config />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/sqlconnection" />
<property name="username" value="admin" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>ee.st.running.model.Client</value>
<value>ee.st.running.dao.ClientDAOImpl</value>
<value>ee.st.running.model.Order</value>
<value>ee.st.running.dao.OrderDAOImpl</value>
</list>
</property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
</bean>
<bean id = "client" class = "ee.st.running.model.Client">
<property name="clientDAO" ref = "ClientDAO"></property>
</bean>
<bean id = "clientDAO" class = "ee.st.running.dao.ClientDAOImpl">
<property name="sessionFactory" ref = "sessionFactory"></property>
</bean>
<bean id = "order" class = "ee.st.running.model.Order">
<property name="orderDAO" ref = "OrderDAO"></property>
</bean>
<bean id = "orderDAO" class = "ee.st.running.dao.OrderDAOImpl">
<property name="sessionFactory" ref = "sessionFactory"></property>
</bean>
</beans>
And here is the project structure:
And here is my pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ee.st.running.aktorstask</groupId>
<artifactId>aktorstask</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.2.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.3.0.ga</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
<properties>
<spring.version>3.2.3.RELEASE</spring.version>
</properties>
</project>
And the classes:
Client
package ee.st.running.model;
//import java.util.List;
//import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
//import javax.persistence.OneToMany;
import javax.persistence.Table;
import ee.st.running.dao.ClientDAOInterface;
import ee.st.running.dao.ClientDAOImpl;
#Entity
#Table(name = "client")
public class Client implements ClientInterface {
private Order o;
ClientDAOInterface ClientDAOInterface;
#Id
#GeneratedValue
private int id;
#Column (name = "name")
private String name;
#Column (name = "surename")
private String surename;
#Column (name = "address")
private String address;
#Column (name = "phone_number")
private long phoneNumber;
#Column (name = "id_code")
private long idCode;
//#OneToMany(mappedBy = «client», fetch = FetchType.LAZY)
public void makeorder() {
o.newOrder();
}
// getters nd setters
public Order getO() {
return o;
}
public void setO(Order o) {
this.o = o;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurename() {
return surename;
}
public void setSurename(String surename) {
this.surename = surename;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
public long getIdCode() {
return idCode;
}
public void setIdCode(int idCode) {
this.idCode = idCode;
}
// ctor
public Client ()
{
}
public void setClientInfDAO (ClientDAOInterface ClientDAOInterface)
{
this.ClientDAOInterface = ClientDAOInterface;
}
public void save(Client client) {
ClientDAOInterface.save(client);
}
public void update(Client client) {
ClientDAOInterface.update(client);
}
public void remove(Client client) {
ClientDAOInterface.remove(client);
}
}
ClientInterface:
package ee.st.running.model;
public interface ClientInterface {
public void makeorder ();
public void save(Client client);
public void update (Client client);
public void remove (Client client);
}
ClientDAOInterface:
package ee.st.running.dao;
import java.util.List;
import ee.st.running.model.Client;
public interface ClientDAOInterface {
public void removeClient (long id);
public List<Client> listClient();
public void save (Client client);
public void update (Client client);
public void remove (Client client);
}
ClientDAOImpl:
package ee.st.running.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import ee.st.running.model.Client;
#Repository
public class ClientDAOImpl extends HibernateDaoSupport implements ClientDAOInterface {
#Autowired
private SessionFactory sessionFactory;
public void AddClient(Client client) {
sessionFactory.getCurrentSession().save(client);
}
public void removeClient(long id) {
Client client = (Client) sessionFactory.getCurrentSession().load(Client.class, id);
if (null != client) {
sessionFactory.getCurrentSession().delete(client);
}
}
#SuppressWarnings("unchecked")
public List<Client> listClient() {
return sessionFactory.getCurrentSession().createQuery("from Client").list();
}
public void save(Client client) {
sessionFactory.getCurrentSession().save(client);
}
public void update(Client client) {
// TODO Auto-generated method stub
}
public void remove(Client client) {
// TODO Auto-generated method stub
}
}
And lastly my hibernate.cfg:
<?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="ee.st.running.model.Client" />
<mapping class="ee.st.running.model.Order" />
</session-factory>
</hibernate-configuration>
I modified it several times, adding some additional info. What I currently want is to check, whether it works, so in the Main class I wrote primitive code to store info to database and see whether it actually stored, so I could move on:
package ee.st.running.aktorstask;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import ee.st.running.dao.*;
import ee.st.running.model.*;
public class Main {
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext ("./config.xml");
Client clientx = (Client) appContext.getBean("client");
Client client = new Client ();
client.setName("Vasilij");
client.setIdCode(389844455);
client.setAddress("Pae 485 54 Tartu");
client.setSurename("B");
//client.makeorder();
clientx.save(client);
}
}
It now gives me mappingexception
Any ideas, why? And, by the way who is "AnnotationConfiguration instance" and where it supposed to be?
Normal hibernate.cfg.xml uses Configuration class for building Sessionfactory object
return new Configuration().configure().buildSessionFactory();
You need to use AnnotationConfiguration for the same.
In your above example you have specified classes in sessionFactory bean as
<property name="annotatedClasses">
<list>
<value>ee.st.running.model.Client</value>
<value>ee.st.running.dao.ClientDAOImpl</value>
<value>ee.st.running.model.Order</value>
<value>ee.st.running.dao.OrderDAOImpl</value>
</list>
</property>
Wrong thing you did here is you added DAO classes also. AnnotatedClasses should be domain classes.
You can remove them and keep only Client and Order in that.
Secondly you have also provided hibernate.cfg.xml file. Hence you can remove that as you are using annotated classes.
Hence final code may look like this:
<property name="annotatedClasses">
<list>
<value>ee.st.running.model.Client</value>
<value>ee.st.running.model.Order</value>
</list>
</property>
And removing hibernate.cfg.xml

Error creating bean with name 'clientsDaoImpl': Injection of autowired dependencies failed;

This error is killing me, i searched a lot of similar topics here, but none of them helped me!
So, i'm using spring MVC+hibernate. Please, just take a look, maybe you will find mistake which i missed!
Here is my files:
Clients
package app.model;
import javax.persistence.*;
#Entity
#Table(name = "clients")
public class Clients {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int client_id;
private String gender;
private String first_name;
private String last_name;
private String country;
private String city;
private String birthdate;
private String phone;
private String email;
private int orders;
private double total_income;
public Clients() {
}
public Clients(int client_id, String gender, String first_name,
String last_name, String country, String city, String birthdate,
String phone, String email, int orders, double total_income) {
super();
this.client_id = client_id;
this.gender = gender;
this.first_name = first_name;
this.last_name = last_name;
this.country = country;
this.city = city;
this.birthdate = birthdate;
this.phone = phone;
this.email = email;
this.orders = orders;
this.total_income = total_income;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public int getClient_id() {
return client_id;
}
public void setClient_id(int client_id) {
this.client_id = client_id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getOrders() {
return orders;
}
public void setOrders(int orders) {
this.orders = orders;
}
public double getTotal_income() {
return total_income;
}
public void setTotal_income(double total_income) {
this.total_income = total_income;
}
}
ClientsService
package app.service;
import java.text.ParseException;
import java.util.List;
import app.model.Clients;
public interface ClientsService {
public void addClient(Clients client);
public void updateClient(Clients client) throws ParseException;
public void deleteClient(Clients client) throws ParseException;
public Clients getClient(int client_id);
public List<Clients> getAllClients();
}
ClientsServiceImpl
package app.service.impl;
import java.text.ParseException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import app.dao.ClientsDao;
import app.model.Clients;
import app.service.ClientsService;
#Service
public class ClientsServiceImpl implements ClientsService {
#Autowired
private ClientsDao clientsDao;
public ClientsServiceImpl() {
}
public List<Clients> getAllClientsList() {
return clientsDao.getAllClients();
}
#Transactional
public void addClient(Clients client) {
clientsDao.addClient(client);
}
#Transactional
public void updateClient(Clients client) throws ParseException{
clientsDao.updateClient(client);
}
#Transactional
public void deleteClient(Clients client) throws ParseException{
clientsDao.deleteClient(client);
}
#Transactional
public Clients getClient(int client_id) {
return clientsDao.getClient(client_id);
}
#Transactional
public List<Clients> getAllClients() {
return clientsDao.getAllClients();
}
}
ClientsDao
package app.dao;
import java.text.ParseException;
import java.util.List;
import app.model.Clients;
public interface ClientsDao {
public void addClient(Clients client);
public void updateClient(Clients client) throws ParseException;
public void deleteClient(Clients client) throws ParseException;
public Clients getClient(int client_id);
public List<Clients> getAllClients();
}
ClientsDaoImpl
package app.dao.impl;
import java.text.ParseException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import app.model.Clients;
import app.dao.ClientsDao;
import app.logic.Similar;
#Repository
public class ClientsDaoImpl implements ClientsDao {
#Autowired
public SessionFactory session;
public ClientsDaoImpl() {
}
#Transactional
#SuppressWarnings("unchecked")
public List<Clients> getAllClients() {
return session.getCurrentSession().createQuery("from Clients").list();
}
#Transactional
public void addClient(Clients client) { // add new client
session.getCurrentSession().save(client);
}
#Transactional
public void updateClient(Clients client) throws ParseException { // update client
session.getCurrentSession().update(client);
}
#Transactional
public void deleteClient(Clients client) throws ParseException { // delete client if he\she doesnt have any orders
session.getCurrentSession().delete(client);
}
#Transactional
public Clients getClient(int client_id) {
return (Clients)session.getCurrentSession().get(Clients.class, client_id);
}
}
ClientsController
package app.controller;
import java.text.ParseException;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import app.model.Clients;
import app.service.ClientsService;
#Controller
public class ClientsController {
#Autowired
public ClientsService clientsService;
public ClientsController(){
}
#RequestMapping("/index")
public String setupForm(Map<String, Object> map) {
Clients client = new Clients();
map.put("client", client);
map.put("clientsList", clientsService.getAllClients());
return "client";
}
#RequestMapping(value = "/client.do", method = RequestMethod.POST)
public String doActions(#ModelAttribute Clients client,
BindingResult result, #RequestParam String action,
Map<String, Object> map) throws ParseException {
Clients clientResult = new Clients();
switch (action.toLowerCase()) {
case "add":
clientsService.addClient(client);
clientResult = client;
break;
case "edit":
clientsService.updateClient(client);
clientResult = client;
break;
case "delete":
clientsService.deleteClient(client);
clientResult = new Clients();
break;
case "search":
Clients searchedClient = clientsService.getClient(client.getClient_id());
clientResult = searchedClient != null ? searchedClient : new Clients();
break;
}
map.put("client", clientResult);
map.put("clientsList", clientsService.getAllClients());
return "client";
}
}
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"
id="WebApp_ID" version="3.0">
<display-name>ProjectMVC</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/projectdb
jdbc.username=root
jdbc.password=root
spring-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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="app.*">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<context:spring-configured />
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<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="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>
<tx:annotation-driven />
<aop:config proxy-target-class="true"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Project</groupId>
<artifactId>Project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<org.springframework.version>3.0.5.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Hibernate resources -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.3.0.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.2.GA</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>20030825.184428</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>20030825.183949</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- Log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<testSourceDirectory>src/main/test</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/webapp</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
upd: forgot hibernate.cfg
<?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="app.model.Clients" />
</session-factory>
</hibernate-configuration>
Possibly try this solution from here: Getting a org.springframework.beans.factory.BeanCreationException with my first Maven, Spring Project
just add:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${your-spring-version}</version>
</dependency>
I think your missing the repository name in your ClientsDaoImpl .
#Repository("clientsDAO")
public class ClientsDaoImpl implements ClientsDao.....

Java+Spring: SEVERE Servletservice

I dont know what is wrong in my listContacts in controller
map.put("contactList", contactService.listContact());
Can somebody help me?
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/test] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at pl.ivmx.contact.controller.ContactController.listContacts(ContactController.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
package pl.ivmx.contact.controller;
import java.util.Map;
import pl.ivmx.contact.dao.ContactDAO;
import pl.ivmx.contact.form.Contact;
import pl.ivmx.contact.service.ContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class ContactController {
#Autowired
private ContactService contactService;
#RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "/contact";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact") Contact contact,
BindingResult result) {
contactService.addContact(contact);
return "redirect:/contact";
}
#RequestMapping("/delete/{contactId}")
public String deleteContact(#PathVariable("contactId") Integer contactId) {
contactService.removeContact(contactId);
return "redirect:/contact";
}
}
package pl.ivmx.contact.dao;
import java.util.List;
import pl.ivmx.contact.form.Contact;
public interface ContactDAO {
public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
}
package pl.ivmx.contact.dao;
import java.util.List;
import pl.ivmx.contact.form.Contact;
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);
}
public List<Contact> listContact() {
return sessionFactory.getCurrentSession().createQuery("from Contact").list();
}
public void removeContact(Integer id) {
Contact contact = (Contact) sessionFactory.getCurrentSession().load(
Contact.class, id);
if (null != contact) {
sessionFactory.getCurrentSession().delete(contact);
}
}
}
package pl.ivmx.contact.service;
import java.util.List;
import pl.ivmx.contact.form.Contact;
public interface ContactService {
public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
}
package pl.ivmx.contact.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.ivmx.contact.dao.ContactDAO;
import pl.ivmx.contact.form.Contact;
#Service
public class ContactServiceImpl implements ContactService {
#Autowired
private ContactDAO contactDAO;
#Transactional
public void addContact(Contact contact) {
contactDAO.addContact(contact);
}
#Transactional
public List<Contact> listContact() {
return contactDAO.listContact();
}
#Transactional
public void removeContact(Integer id) {
contactDAO.removeContact(id);
}
}
package pl.ivmx.contact.form;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="CONTACTS")
public class Contact {
#Id
#Column(name="ID")
#GeneratedValue
private Integer id;
#Column(name="FIRSTNAME")
private String firstname;
#Column(name="LASTNAME")
private String lastname;
#Column(name="EMAIL")
private String email;
#Column(name="TELEPHONE")
private String telephone;
public String getEmail() {
return email;
}
public String getTelephone() {
return telephone;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
<?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_3_0.xsd"
id="WebApp_ID" version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/pages/index.jsp</welcome-file>
</welcome-file-list>
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:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="pl.ivmx.contact" />
<!-- <bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="messages_en.properties" />
<property name="defaultEncoding" value="UTF-8" />
</bean> -->
<import resource="commonContext.xml" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="userTestDao" class="pl.ivmx.dao.impl.UserTestDaoImpl">
<!-- <property name="dataSource" ref="dataSource" /> -->
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
<!-- class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> -->
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="META-INF/hibernate.cfg.xml" />
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<!-- <property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>pl.ivmx.model.UserTest</value>
</list>
</property> -->
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
dispatcher-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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/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">
<!-- <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/index.do"> <ref bean="index" /></entry>
<entry key="/registration.do"> <ref bean="registration" /></entry>
<entry key="/usertestlist.do"> <ref bean="usertest" /></entry>
<entry key="/contact.do"> <ref bean="contact" /></entry>
</map>
</property>
</bean>
<bean id="index" class="pl.ivmx.web.IndexController"/>
<bean id="registrationValidator" class="pl.ivmx.validation.RegistrationValidator" />
<bean id="registration" class="pl.ivmx.web.RegistrationFormController" >
<property name="commandName"><value>userTest</value></property>
<property name="commandClass"><value>pl.ivmx.model.UserTest</value></property>
<property name="validator"><ref local="registrationValidator"/></property>
<property name="formView"><value>registration</value></property>
<property name="successView"><value>registrationsuccess</value></property>
<property name="userTestDao"><ref bean="userTestDao"/></property>
</bean>
<bean id="usertest" class="pl.ivmx.web.UserTestController">
<property name="userTestDao"><ref bean="userTestDao"/></property>
</bean>
<bean id="contact" class="pl.ivmx.contact.controller.ContactController">
</bean>
<bean id="contactService" class="pl.ivmx.contact.service.ContactServiceImpl">
</bean>
<bean id="contactDAO" class="pl.ivmx.contact.dao.ContactDAOImpl">
</bean>
</beans>
It looks like a NullPointerException thrown in the method here:
#RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "/contact";
}
I would debug and check that contactService has been autowired correctly.
The null pointer is line 26, if that is the line containing contactService.listContact() then contactService is null. If it is the line above then the map is null.
I am not sure but try adding:
<context:component-scan base-package="pl.ivmx.contact" />
to the dispatcher-servlet.xml as well, it could be that the annotation isnt getting processed
you are returning "/contact" there in the method as a view to be shown:
#RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "/contact"; // <---- here!
}
This means that you should have a view named /contact defined somewhere, but I don't see it. You need to have a view that corresponds with the value you're defining.
You probably want to return a value like "contact" instead of "/contact" and then have contact.jsp in the webapp/WEB-INF/views folder (assuming you use maven standard directory layout).
I don't see anything obvious ... could sessionFactory be null? Should be easy to find, tho. Step through the code in the debugger.
I think you are missing to add the contactService bean to your applicationContext.xml
try adding the below to tags
<bean id="contactService" class="pl.ivmx.contact.service.ContactServiceImpl">
<property name="contactDAO" ref="contactDAO" />
</bean>
<bean id="contactDAO" class="pl.ivmx.contact.dao.ContactDAOImpl" />

Categories