Custom Validation messages spring not being displayed - java

I am currently using the following environment:
Netbeans 8
Jdk 1.7
Spring 4
Hibernate 5.0.1
Bean validator 1.1
I have got the following files:
Servlet configuration (Spring):
<context:component-scan base-package="mz.co.hypervision.web" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
Student class:
public class Student {
#NotNull(message = "{age.notnull}")
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
Message properties file:
Location: SpringTest\build\web\WEB-INF\classes
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
age.notnull=The age of the student may not be null
UPDATED
Controller code:
import javax.validation.Valid;
import mz.co.hypervision.domain.Student;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
#Controller
public class StudentController {
#RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "student", new Student());
}
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("student") #Valid Student student,
BindingResult result, ModelMap model) {
if(result.hasErrors()) {
return "student";
} else {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
}
Please check below that the message appears as {age.notnull}:
Image with the situation
Please assist in figuring out why it is not working, as per my view I have followed every step to make it happen

The issue was solved by adding the messages.properties file to the java classpath

Related

UnsatisfiedDependencyException: Error creating bean with name "empController"

I want to learn Spring, so I write simple java CRUD app. But from the begining have errors org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empController'" and org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dao' for my servlet. I was looking some solutions, but nothing works.
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Employer</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Employer</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Employer-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.javatpoint"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/Employers"></property>
<property name="username" value="root"></property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.javatpoint.EmpDao">
<property name="jdbcTemplate" ref="jt"></property>
</bean>
</beans>
EmpController.java
package com.javatpoint;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class EmpController {
#Autowired
EmpDao empDao;
#RequestMapping("/empform")
public ModelAndView show() {
return new ModelAndView("empform", "command", new Emp());
}
#RequestMapping(value="/save", method=RequestMethod.POST)
public ModelAndView save(#ModelAttribute("emp")Emp emp) {
empDao.save(emp);
return new ModelAndView("redirect:/viewemp");
}
#RequestMapping("/viewemp")
public ModelAndView viewemp() {
List<Emp> list = empDao.getEmployees();
return new ModelAndView("viewemp", "list", list);
}
#RequestMapping(value="/editemp/{id}")
public ModelAndView edit(#PathVariable("id")int id) {
Emp emp = empDao.getById(id);
return new ModelAndView("empeditform", "command", emp);
}
#RequestMapping(value="editsave", method=RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("emp")Emp emp) {
empDao.update(emp);
return new ModelAndView("redirect:/viewemp");
}
#RequestMapping("/delete")
public ModelAndView delete(#ModelAttribute("emp")Emp emp) {
empDao.delete(emp);
return new ModelAndView("redirect:/viewemp");
}
}
EmpDao.java
package com.javatpoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class EmpDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int save(Emp emp) {
String sql = "insert into Employers values('"+emp.getId()+"','"+emp.getName()+"','"+emp.getSalary()+"','"+emp.getDesignation()+"')";
return jdbcTemplate.update(sql);
}
public int update(Emp emp) {
String sql = "update Employers set name='"+emp.getName()+"',salary='"+emp.getSalary()+"',designation='"+emp.getDesignation()+"' where id='"+emp.getId()+"'";
return jdbcTemplate.update(sql);
}
public int delete(Emp emp) {
String sql = "delete from Employers where id='"+emp.getId()+"'";
return jdbcTemplate.update(sql);
}
public Emp getById(int id) {
String sql = "select * form Employers where id=?";
return jdbcTemplate.queryForObject(sql, new Object[] {id}, new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return jdbcTemplate.query("select * from Employers", new RowMapper<Emp>() {
public Emp mapRow(ResultSet rs, int row) throws SQLException{
Emp emp = new Emp();
emp.setId(rs.getInt(1));
emp.setName(rs.getString(2));
emp.setSalary(rs.getFloat(3));
emp.setDesignation(rs.getString(4));
return emp;
}
});
}
}
Emp.java
package com.javatpoint;
public class Emp {
private int id;
private String name;
private float salary;
private String designation;
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;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
The main problem is that you're trying to autowire an EmpDao to your controller without havin an EmpDao bean.
In order to make EmpDao a bean you should annotate the EmpDao class with #Component , #Service or #Repository:
#Service
public class EmpDao {
#Autowired
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int save(Emp emp) {
String sql = "insert into Employers values('"+emp.getId()+"','"+emp.getName()+"','"+emp.getSalary()+"','"+emp.getDesignation()+"')";
return jdbcTemplate.update(sql);
}
public int update(Emp emp) {
String sql = "update Employers set name='"+emp.getName()+"',salary='"+emp.getSalary()+"',designation='"+emp.getDesignation()+"' where id='"+emp.getId()+"'";
return jdbcTemplate.update(sql);
}
public int delete(Emp emp) {
String sql = "delete from Employers where id='"+emp.getId()+"'";
return jdbcTemplate.update(sql);
}
public Emp getById(int id) {
String sql = "select * form Employers where id=?";
return jdbcTemplate.queryForObject(sql, new Object[] {id}, new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return jdbcTemplate.query("select * from Employers", new RowMapper<Emp>() {
public Emp mapRow(ResultSet rs, int row) throws SQLException{
Emp emp = new Emp();
emp.setId(rs.getInt(1));
emp.setName(rs.getString(2));
emp.setSalary(rs.getFloat(3));
emp.setDesignation(rs.getString(4));
return emp;
}
});
}
}
Remember, you can only inject (or autowire) other beans into your beans.
In spring, the application creates it's own beans (either as singletons, or a 'new' instance anytime you need it.)
EmpController for example is annotated with #Controller to tell spring exactly that- this is a controller, as the application starts up, please create a new instance of this bean, so I can use it.
However, as spring tries to create this bean, it also populates it's variables.
#Autowired on the empDao variable means roughly: "you should already have built an instance of the class empDao, so please, let me have here a reference to it(empDao) so I can call it from this class(empController)"
#Controller
public class EmpController {
#Autowired
EmpDao empDao;
But it seems empDao itself is not configured properly- no annotation to let spring know it should create an instance of it while starting up.
try the following 2 changes:
#Service
public class EmpDao {
and
#Entity
public class Emp {

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL)

While Executing the program, I'm getting the particular error
**Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException:
Write operations are not allowed in read-only mode (FlushMode.MANUAL):
Turn your Session into FlushMode.
COMMIT/AUTO or remove 'readOnly' marker from transaction definition.**
every time. please someone help me. Here I am giving my codes which contains some error. In the Below code I have taken one employee data which will be stored in the employee table of MSSQL database. While working with only hibernate at that time i can able to persist my data. But, her i am unable to persist my data.
EmployeeHt.java
This is the entity class which is mapped to the employee table of MSSQL database
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee")
public class EmployeeHt {
#Id
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#Column(name="salary")
private int 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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
#Override
public String toString() {
return "EmployeeHt [id=" + id + ", name=" + name + ", salary=" + salary + "]";
}
}
EmployeeHtDao.java
This is the class which contains hibernate template
import org.springframework.orm.hibernate5.HibernateTemplate;
public class EmployeeHtDao {
private HibernateTemplate ht;
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
public void saveEmployee(EmployeeHt e){
ht.save(e);
}
}
EmployeeHtTest.java
**This is the main class**
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class EmployeeHtTest {
private static ApplicationContext context;
public static void main(String[] args) {
context = new ClassPathXmlApplicationContext("hibernateTemplate.xml");
EmployeeHtDao dao=(EmployeeHtDao) context.getBean("edao");
EmployeeHt e=new EmployeeHt();
e.setId(104);
e.setName("Prangyan");
e.setSalary(30000);
dao.saveEmployee(e);
}
}
hibernateTemplate.xml
**This is the spring-xml file**
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="connpool" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=ananta"/>
<property name="username" value="sa"/>
<property name="password" value="pass123"/>
</bean>
<bean id="mysessionfactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="connpool"/>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionfactory"/>
</bean>
<bean id="edao" class="com.sdrc.hibernatetemplate.EmployeeHtDao">
<property name="ht" ref="hibernateTemplate"/>
</bean>
</beans>
Check for #Transactional annotation in you DAO.
It should be
#Transactional(readOnly = false)

#Vaild is not working

I want to check size validation for studentHobby object and i am using #Size annotation and Using #valid annotation.
I am providing less than the value defined in #Size annotation but still I am getting the result instead of error.
I tried things but didn't come with solutions.
StudentAdmissionController.java
package com.diwakar;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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.servlet.ModelAndView;
#Controller
public class StudentAdmissionController {
#InitBinder
public void initBinder(WebDataBinder binder) {
//binder.setDisallowedFields(new String[] {"studentMobile"});
//SimpleDateFormat date = new SimpleDateFormat("dd**MM**yyyy");
//binder.registerCustomEditor(Date.class, "studentDOB", new CustomDateEditor(date, false));
binder.registerCustomEditor(String.class, "studentName", new StudentNameEditor());
}
#RequestMapping(value="/admission.html", method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {
ModelAndView model = new ModelAndView("AdmissionForm");
//model.addObject("headerMessage", "Diwakar College of Engineering.!!");
return model;
}
#RequestMapping(value="/submitForm", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(#Valid #ModelAttribute("st1") Student st1, BindingResult result) {
if (result.hasErrors()) {
ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}
ModelAndView model = new ModelAndView("AdmissionSuccess");
//model.addObject("headerMessage", "Diwakar College of Engineering.!!");
return model;
}
#ModelAttribute
public void addCommonMessage(Model model) {
model.addAttribute("headerMessage", "Diwakar College of Engineering.!!");
}
Student.java
package com.diwakar;
import java.util.ArrayList;
import java.util.Date;
import javax.validation.constraints.Size;
public class Student {
private String studentName;
#Size(min=3, max=10)
private String studentHobby;
private Long studentMobile;
private Date studentDOB;
private ArrayList<String> studentSkills;
private Address studentAddress;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentHobby() {
return studentHobby;
}
public void setStudentHobby(String studentHobby) {
this.studentHobby = studentHobby;
}
public Long getStudentMobile() {
return studentMobile;
}
public void setStudentMobile(Long studentMobile) {
this.studentMobile = studentMobile;
}
public Date getStudentDOB() {
return studentDOB;
}
public void setStudentDOB(Date studentDOB) {
this.studentDOB = studentDOB;
}
public ArrayList<String> getStudentSkills() {
return studentSkills;
}
public void setStudentSkills(ArrayList<String> studentSkills) {
this.studentSkills = studentSkills;
}
public Address getStudentAddress() {
return studentAddress;
}
public void setStudentAddress(Address studentAddress) {
this.studentAddress = studentAddress;
}
}
spring-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- <bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<bean name="/welcome.html" class="com.diwakar.HelloController" /> -->
<context:component-scan base-package="com.diwakar" />
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
Here is my admission page even though i am providing one one character it is giving me submit form instead of error.
admission.html Page
This submit form i am getting after submitting value with 1 character.
submitForm

Getting error "Injection of autowired dependencies failed;" when adding another entity class to annotedClasses list in spring

Please help me I am totally stuck at one thing.
In my program everything was running fine when I was working with only one entity class called Person but when i have added one more entity class called Specimen it throws me exception like "hibernate exception unknown entity Specimen" after searching on google I have added "Specimen" class in annottedClasses list but after adding it throwing me exception
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'homeController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private com.swapnil.service.RegisterService
Below is my code:
Home controller:
package com.swapnil.controller;
import javax.validation.Valid;
import org.omg.CORBA.portable.ApplicationException;
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 com.swapnil.models.Person;
import com.swapnil.models.User;
import com.swapnil.service.RegisterService;
#Controller
public class HomeController {
#Autowired
private RegisterService registerService;
#RequestMapping(value = "/", method = { RequestMethod.GET,
RequestMethod.POST })
public String welcomePage(ModelMap map) {
System.out.println("*****");
map.addAttribute("message", "Welcome to Spring mvc");
return "welcome";
}
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String displayregistrationPage(Model map) {
User userObj = new User();
map.addAttribute("user", userObj);
return "register";
}
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String doRegistration(#Valid #ModelAttribute("user") User user,
BindingResult result, Model model) {
int id = 0;
System.out.println(user);
if (result.hasErrors()) {
return "register";
} else {
if (!registerService.checkUser(user)) {
try {
id = registerService.addUser(user);
} catch (ApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
model.addAttribute("userid", id);
return "login";
}
#RequestMapping(value = "/shortregister", method = { RequestMethod.GET })
public String shortregister(Model map) {
Person personObj = new Person();
map.addAttribute("person", personObj);
return "shortReg";
}
#RequestMapping(value = "/shortregister", method = { RequestMethod.POST })
public String shortregisterDo(Model map,
#Valid #ModelAttribute("person") Person person, BindingResult result) {
if (result.hasErrors()) {
// throw new CustomGenericException("407",
// "something is missing required for registration");
return "shortReg";
} else {
registerService.addPerson(person);
return "welcome";
}
}
}
personDAO:-
package com.swapnil.dao;
import java.util.List;
import com.swapnil.models.Person;
import com.swapnil.models.Specimen;
public interface PersonDAO {
public void save(Person p);
public List<Person> list();
public int addSpecimen(Specimen specimen);
}
personDAOImpl--
package com.swapnil.dao;
import java.util.List;
import javax.sql.DataSource;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.swapnil.models.Person;
import com.swapnil.models.Specimen;
#Repository
public class PersonDAOImpl implements PersonDAO {
protected SessionFactory sessionFactory;
protected DataSource ds;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public DataSource getDs() {
return ds;
}
public void setDs(DataSource ds) {
this.ds = ds;
}
#Override
#Transactional
public void save(Person p) {
// TODO Auto-generated method stub
System.out.println("session factipwpf " + sessionFactory);
Session session = sessionFactory.openSession();
System.out.println("sesstion " + session);
// System.out.println("connection "+session.connection());
Transaction tx = session.beginTransaction();
System.out.println(p);
// System.out.println("last saved user "+session.save(p));
// session.persist(p);
// System.out.println("persist id "+session.getIdentifier(p));
SQLQuery query = session
.createSQLQuery("insert into person(id,name,country) values(:id,:name,:country)");
query.setParameter("id", p.getId());
query.setParameter("name", p.getName());
query.setParameter("country", p.getCountry());
query.executeUpdate();
tx.commit();
session.close();
}
#Override
public List<Person> list() {
// TODO Auto-generated method stub
Session session = sessionFactory.openSession();
Query query = session.createQuery("from person");
List<Person> plist = query.list();
return plist;
}
#Override
#Transactional
public int addSpecimen(Specimen specimen) {
// TODO Auto-generated method stub
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
int id = (Integer) session.save(specimen);
tx.commit();
return id;
}
}
RegisterService--
package com.swapnil.service;
import com.swapnil.models.Person;
import com.swapnil.models.Specimen;
import com.swapnil.models.User;
public interface RegisterService {
public Boolean checkUser(User user);
public int addUser(User user);
public int addPerson(Person person);
public int addspecimen(Specimen specimen);
}
RegisterServiceImpl--
package com.swapnil.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.swapnil.dao.PersonDAO;
import com.swapnil.models.Person;
import com.swapnil.models.Specimen;
import com.swapnil.models.User;
#Service
public class RegisterServiceImpl implements RegisterService {
#Autowired
PersonDAO personDAO;
#Override
public Boolean checkUser(User user) {
boolean userPresentFlag = false;
if (null != user) {
if (user.getFname().equalsIgnoreCase("swapnil")) {
userPresentFlag = true;
}
}
return userPresentFlag;
}
#Override
public int addUser(User user) {
int id;
if (null == user) {
throw new NullPointerException();
} else {
id = user.getUserid();
}
return id;
}
#Override
public int addPerson(Person person) {
personDAO.save(person);
return 0;
}
#Override
public int addspecimen(Specimen specimen) {
return personDAO.addSpecimen(specimen);
}
}
below is the my configuration file-
<?xml version="1.0" encoding="UTF-8"?>
<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: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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="com.swapnil.controller"/>
<context:component-scan base-package="com.swapnil.service"/>
<context:component-scan base-package="com.swapnil.dao"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:annotation-driven/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"/>
<property name="username" value="swapnil" />
<property name="password" value="swapnil" />
</bean>
<bean id="hibernate3AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.swapnil.models.Person</value>
<value>com.swapnil.models.Specimen</value>
</list>
</property>
<!-- <property name="packagesToScan" value="com.swapnil.models" ></property> -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.default_schema">SWAPNIL</prop>
</props>
</property>
</bean>
<bean id="personDAO" class="com.swapnil.dao.PersonDAOImpl">
<property name="sessionFactory" ref="hibernate3AnnotatedSessionFactory" />
</bean>
</beans>
every thing was fine before adding com.swapnil.models.Specimen in configuration file please help me.
below is the snap of Specimen class
Specimen---
package com.swapnil.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name = "SPECIMEN_DETAILS")
public class Specimen {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SPECIMEN_DETAILS_SEQ")
private int id;
#Size(min = 4, max = 8)
#Column(name = "username")
private String username;
#NotNull
#Min(value = 1)
private int specimenid;
#NotNull
#Min(value = 1)
private int projectid;
#NotNull
#Min(value = 1)
private int technologyid;
#Size(min = 4)
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getSpecimenid() {
return specimenid;
}
public void setSpecimenid(int specimenid) {
this.specimenid = specimenid;
}
public int getProjectid() {
return projectid;
}
public void setProjectid(int projectid) {
this.projectid = projectid;
}
public int getTechnologyid() {
return technologyid;
}
public void setTechnologyid(int technologyid) {
this.technologyid = technologyid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Specimen [id=" + id + ", username=" + username
+ ", specimenid=" + specimenid + ", projectid=" + projectid
+ ", technologyid=" + technologyid + ", description="
+ description + "]";
}
}
Try to write the #Service like this:
#Service("registerService")
public class RegisterServiceImpl implements RegisterService {

The type ResultSetExtractor is not generic; it cannot be parameterized with arguments <List<Employee>>

I am learning spring. while creating one example i got error.
The type ResultSetExtractor is not generic; it cannot be parameterized with arguments <List<Employee>>
I implement the app as below
Employee.java
package com.develop;
public class Employee {
private int id;
private String name;
private float salary;
public Employee(){}
public Employee(int id, String name, float salary){
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.develop;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
public class EmployeeDao {
private JdbcTemplate template;
public void setJdbcTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Employee> getAllEmployees(){
return template.query("select * from employee",new ResultSetExtractor<List<Employee>>(){
#Override
public List<Employee> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Employee> list=new ArrayList<Employee>();
while(rs.next()){
Employee e=new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getInt(3));
list.add(e);
}
return list;
}
});
}
}
Test.java
package com.develop;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
List<Employee> list=dao.getAllEmployees();
for(Employee e:list)
System.out.println(e);
}
}
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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="oracle" /> -->
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/springdatabase" />
<property name="username" value="root" />
<property name="password" value="admin123" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.develop.EmployeeDao">
<property name="template" ref="jdbcTemplate"></property>
</bean>
</beans>
Created Table
CREATE TABLE employee(id number(10),NAME varchar2(100),salary number(10));
The error message clearly sais it:
The ResultSetExtractor is not generic.
The interface was made generic in a newer version of Spring. But anyway, you can still use it's raw form, although you'd be forced you do a cast when working with the result of the extractData() method.
public List<Employee> getAllEmployees(){
return template.query("select * from employee",new ResultSetExtractor(){
#Override
public Object extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Employee> list=new ArrayList<Employee>();
while(rs.next()) {
Employee e=new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getInt(3));
list.add(e);
}
return list;
}
});
}
P.S.:
I assume you're using an old version of the Spring Framework, because in the newer version(s), the ResultSetExtractor is actually generic. So, you can either update your Spring version (but be careful, because this might cause you compilation problems and other issues), or stick to the approach used in the code snippet above.

Categories