我正在尝试使用Hibernate在我的spring-mvc
中实现表单验证应用。我在'name'字段
上应用了一个@Size约束我的表格。当我提交表单时,我收到以下错误:
java.lang.IncompatibleClassChangeError:class org.hibernate.ejb.HibernatePersistence将org.hibernate.ejb.AvailableSettings作为超类接口
我的代码:
////////////////////////// SpringConfig //////////////////
@Configuration
@EnableWebMvc
@ComponentScan({ "com." })
@EnableTransactionManagement
public class SpringConfig extends WebMvcConfigurerAdapter {
@Autowired
private Environment environment;
@Autowired
private PersonService ps;
@Bean @Autowired
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setAnnotatedClasses(Person.class);
sessionFactory.setPackagesToScan(new String[] { "com.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean @Autowired
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myschema");
dataSource.setUsername("root");
dataSource.setPassword("admin123");
return dataSource;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/*");
}
@Bean @Autowired
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver res = new InternalResourceViewResolver();
res.setPrefix("/WEB-INF/view/");
res.setSuffix(".jsp");
return res;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect",
"org.hibernate.dialect.MySQL5Dialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "update");
return properties;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
///////////////////////////////////控制器/////////// ////////////////
package com.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import com.model.Person;
import com.service.PersonService;
@Controller
public class MainController {
@Autowired
private PersonService ps;
@RequestMapping("/")
public ModelAndView listPersons(ModelAndView model) throws IOException {
List<Person> listper = ps.list();
model.addObject("personsList", listper);
model.setViewName("index");
return model;
}
@RequestMapping(value = "/newPerson", method = RequestMethod.GET)
public ModelAndView newPerson(ModelAndView model) throws IOException {
@SuppressWarnings("unused")
Person p = new Person();
model.addObject("person", new Person());
model.setViewName("AddPerson");
return new ModelAndView("AddPerson", "person", new Person());
}
@RequestMapping(value="/save",method=RequestMethod.POST)
public String save(@Valid @ModelAttribute Person p,BindingResult result) {
//System.out.println(p.getName());
// ps.getPersonById(p.getId());
if(result.hasErrors())
{
return "redirect:http://localhost:8080/MainAssignment3/AddPerson";
}
else
{
ps.save(p);
return "redirect:http://localhost:8080/MainAssignment3/";
}
}
@RequestMapping("/removePerson")
public String remove(HttpServletRequest req) {
int id = Integer.parseInt(req.getParameter("id"));
ps.removePerson(id);
return "redirect:http://localhost:8080/MainAssignment3/";
}
@RequestMapping("/update")
public String update(@ModelAttribute Person p) {
System.out.println(p.getName());
// ps.getPersonById(p.getId());
ps.save(p);
return "redirect:http://localhost:8080/MainAssignment3/";
}
@RequestMapping("/updatePerson")
public ModelAndView updatePerson(HttpServletRequest req, ModelMap p) {
int id = Integer.parseInt(req.getParameter("id"));
String name = req.getParameter("name");
String address = req.getParameter("address");
String gender = req.getParameter("gender");
String salary = req.getParameter("salary");
p.addAttribute("id", id);
p.addAttribute("name", name);
p.addAttribute("gender", gender);
p.addAttribute("address", address);
p.addAttribute("salary", salary);
return new ModelAndView("updatePerson", "person", p);
}
}
//////////////////////////////// DAOImplementation ////////////// //
package com.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.model.Person;
@Transactional
@Repository
public class PersonDAOImpl implements PersonDAO, java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = (Logger) LoggerFactory
.getLogger(PersonDAOImpl.class);
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
public void save(Person p) {
// TODO Auto-generated method stub
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
s.saveOrUpdate(p);
tx.commit();
s.close();
System.out.println("Record successfully inserted");
}
@SuppressWarnings("deprecation")
public List<Person> list() {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
@SuppressWarnings("unchecked")
List<Person> personsList = session.createQuery("from Person").list();
for (Person p : personsList) {
logger.info("Person List::" + p);
}
return personsList;
}
public void updatePerson(Integer id) {
Session session = new Configuration().configure().buildSessionFactory()
.openSession();
Person p = new Person();
Person person = session.get(Person.class, p.getId());
//Transaction t = session.beginTransaction();
Query query = session.createQuery("from Person");
person.setName(p.getName()); // modify the loaded object somehow
session.update(person);
//t.commit();
session.close();
}
public Person getPersonById(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
logger.info("Person loaded successfully, Person details=" + p);
return p;
}
public void removePerson(Integer id) {
Session session = sessionFactory.getCurrentSession();
// Transaction t = session.beginTransaction();
Person p = (Person) session.load(Person.class, new Integer(id));
session.delete(p);
// t.commit();
logger.info("Person deleted successfully, person details=");
}
}
/////////////////////////////////模型///////////// /////////////////
package com.model;
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.Size;
@Entity
//@Table(name="person")
public class Person {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Size(min=5, max=10, message="Your name should be between 5 - 10 characters.")
private String name;
private String address;
private int salary;
private String gender;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="name")//@NotNull(message = "The name must not be null")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/////////////////////// messagess.properties file /////////////////// < / p>
Size.person.name =名称必须介于{5}和{10}个字符之间
/////////////////////////////的index.jsp ///////////////
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<h2>Hello World!</h2>
<h3><a href="/MainAssignment3/newPerson">Add Person</a></h3>
<table border="1">
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
<th>gender</th>
<th>salary</th>
</tr>
<c:forEach var="person" items='${personsList}' varStatus="status">
<tr>
<td>${person.id}</td>
<td>${person.name}</td>
<td>${person.address}</td>
<td>${person.gender}</td>
<td>${person.salary}</td>
<td>
<a href="/MainAssignment3/updatePerson?id=${person.id}&name=${person.name}&address=${person.address}&gender=${person.gender}&salary=${person.salary}">Edit</a>
<a href="/MainAssignment3/removePerson?id=${person.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
/////////////////////////////////// AddPerson.jsp ///////// /////////////
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Employee</title>
</head>
<body>
<form:form action="/MainAssignment3/save" method="post" modelAttribute="p">
<!-- <input type="hidden" name="id" > -->
name : <input type="text" name="name"> <br/>
address : <input type="text" name="address" ><br/>
gender : <input type="text" name="gender" ><br/>
salary : <input type="text" name="salary" ><br/>
<input type="submit"value="submit">
</form:form>
</body>
</html>