Spring MVC的Hibernate搜索错误

时间:2016-08-19 07:47:57

标签: spring-mvc hibernate-search

我正在尝试学习Hibernate Search。

我有一个带有表单验证的SpringMVC + Hibernate CRUD项目。

该项目完美无缺,但在我添加了Hibernate Search功能后,

显示以下错误

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.config.SpringConfig: Invocation of init method failed; nested exception is java.lang.AbstractMethodError

我的代码:

///////////////////////////// SpringConfig.java/////////////// ////////////

package com.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.model.Person;
import com.service.PersonService;


@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");
        properties.put("hibernate.search.default.directory_provider", "org.hibernate.search.store.impl.FSDirectoryProvider");
        properties.put("hibernate.search.default.indexBase", "H:/MyWorkspace/MainAssignment3/indexes");
        return properties;
    }
    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(s);
        return txManager;
    }

     @Bean
        public MessageSource messageSource() {
            ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
            messageSource.setBasename("messages");
            return messageSource;
        }



}

//////////////////////////////控制器//////////////// /////////////

package com.controller;

import java.io.IOException;
import java.util.ArrayList;
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.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 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 Exception {
        ps.indexPersons();
        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")
    public String save(/*@ModelAttribute*/ @Valid Person p, BindingResult result) {

        if(result.hasErrors())
        {

            return "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*/ @Valid Person p1,BindingResult result,Model p) {
        System.out.println(p1.getName());
        int id=p1.getId();
        // ps.getPersonById(p.getId());
        p.addAttribute("p1", p1);
        p.addAttribute("id", id);
        p.addAttribute("name", p1.getName());
        p.addAttribute("gender", p1.getGender());
        p.addAttribute("address", p1.getAddress());
        p.addAttribute("salary", p1.getSalary());

        if(result.hasErrors())
        {

            return "redirect:http://localhost:8080/MainAssignment3/updatePerson";
        }
        else{           

        ps.save(p1);

        return "redirect:http://localhost:8080/MainAssignment3/";

    }
}

    @RequestMapping("/updatePerson")
    public ModelAndView updatePerson(HttpServletRequest req, ModelMap p1,@ModelAttribute Person p) {
        p1.addAttribute("person",new Person());
        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");

        p1.addAttribute("id", id);
        p1.addAttribute("name", name);
        p1.addAttribute("gender", gender);
        p1.addAttribute("address", address);
        p1.addAttribute("salary", salary);
        p1.addAttribute("p1",new Person());
        return new ModelAndView("updatePerson", "person", new Person());

    }

       @RequestMapping(value = "/search", method = RequestMethod.GET)
       public ModelAndView searchPage()
       {
          ModelAndView mav = new ModelAndView("search");
          return mav;
       }

       @RequestMapping(value = "/doSearch", method = RequestMethod.POST)
       public ModelAndView search(@RequestParam("searchText")String searchText) throws Exception
       {
          List<Person> allFound = ps.searchForPerson(searchText);
          List<Person> bookModels = new ArrayList<Person>();

          for (Person p : allFound)
          {
             Person pm = new Person();
            pm.setName(p.getName());
            pm.setAddress(p.getAddress());
            pm.setGender(p.getGender());
            pm.setSalary(p.getSalary());


             bookModels.add(pm);
          }

          ModelAndView mav = new ModelAndView("foundPersons");
          mav.addObject("foundPersons", bookModels);
          return mav;
       }

}

////////////////////////////////库////////////// //////////

package com.dao;

import java.util.List;




import com.model.Person;

public interface PersonDAO {
    public void save(Person p);

    public List<Person> list();

    public void updatePerson(Integer id);

    public Person getPersonById(int id);

    public void removePerson(Integer id);

    public void indexPersons() throws Exception;

    public List<Person> searchForPerson(String searchText) throws Exception;

}

////////////////////////////////的实施 /////// /////////////////

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.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
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=");

    }
    @Transactional
    public void indexPersons() throws Exception{
        // TODO Auto-generated method stub
          try
          {
             Session session = sessionFactory.getCurrentSession();

             FullTextSession fullTextSession = Search.getFullTextSession(session);
             fullTextSession.createIndexer().startAndWait();
          }
          catch(Exception e)
          {
             throw e;
          }
       }

    public List<Person> searchForPerson(String searchText) throws Exception{
        // TODO Auto-generated method stub
        try
          {
             Session session = sessionFactory.getCurrentSession();

             FullTextSession fullTextSession = Search.getFullTextSession(session);

             QueryBuilder qb = fullTextSession.getSearchFactory()
               .buildQueryBuilder().forEntity(Person.class).get();
             org.apache.lucene.search.Query query = qb
               .keyword().onFields("name", "address", "salary","gender")
               .matching(searchText)
               .createQuery();

             org.hibernate.Query hibQuery = 
                fullTextSession.createFullTextQuery(query, Person.class);

             List<Person> results = hibQuery.list();
             return results;
          }
          catch(Exception e)
          {
             throw e;
          }
       }


    }

////////////////////////// MODEL //////////////////// ////////

package com.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Store;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;


@Entity
public class Person {


    @Id     
    @GeneratedValue(strategy=GenerationType.AUTO)   
    private Integer id;
    @NotEmpty @NotNull(message="Name is required!")
    @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
    private String name;
     @Size(min=5, max=10, message="Your address should be between 5 - 10 characters.")
     @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
    private String address;

     @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
    private Integer salary;
     @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
    private String gender;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public Integer getSalary() {
        return salary;
    }
    public void setSalary(Integer salary) {
        this.salary = salary;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }

}

////////////////////////////////服务////////////// ///////////////////

package com.service;

import java.util.List;

import com.model.Person;

public interface PersonService {
    public void save(Person p);

    public List<Person> list();

    public void updatePerson(Integer id);

    public Person getPersonById(int id);

    public void removePerson(Integer id);

public void indexPersons() throws Exception;

    public List<Person> searchForPerson(String searchText) throws Exception;


}

////////////////////////////////////// 服务实施 /////////////

package com.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dao.PersonDAO;
import com.model.Person;

@Service("PersonService")
public class PersonServiceImpl implements PersonService {
    @Autowired
    private PersonDAO pdao;

    @Transactional
    public void save(Person p) {
        // TODO Auto-generated method stub
        pdao.save(p);
    }

    public List<Person> list() {
        // TODO Auto-generated method stub
        return pdao.list();
    }

    public void updatePerson(Integer id) {
        // TODO Auto-generated method stub
        pdao.updatePerson(id);
    }

    public Person getPersonById(int id) {
        // TODO Auto-generated method stub
        return this.pdao.getPersonById(id);
    }

    public void removePerson(Integer id) {
        // TODO Auto-generated method stub
        pdao.removePerson(id);
    }

    public void indexPersons() throws Exception {
        // TODO Auto-generated method stub
        pdao.indexPersons();
    }

    public List<Person> searchForPerson(String searchText) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }


}

//////////////////////////////的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 uri="http://www.springframework.org/tags/form"
    prefix="springForm"%>
<%@ 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>
    <td>name<springForm:errors path='${p.name}' /></td> 
        <td>address<springForm:errors path='${p.address}' /></td>
    <td>gender<springForm:errors path='${p.gender}' /></td>     

    <td>salary<springForm:errors path='${p.salary}' /></td></tr>    
 <c:forEach var="p" items='${personsList}' varStatus="status">
    <tr>

        <td>${p.id}</td>
        <td>${p.name}</td>
        <td>${p.address}</td>
        <td>${p.gender}</td>
        <td>${p.salary}</td>
        <td>
        <a href="/MainAssignment3/updatePerson?id=${p.id}&name=${p.name}&address=${p.address}&gender=${p.gender}&salary=${p.salary}">Edit</a>
            <a href="/MainAssignment3/removePerson?id=${p.id}">Delete</a>
        </td>

    </tr>

</c:forEach> 


</table>

    </body>
</html>

///////////////////////////////////的 search.jsp的 // ////////////////

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@ taglib uri="http://www.springframework.org/tags/form"
    prefix="springForm"%>
<%@ 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>Search Page</title>
</head>
<body>
<springForm:form action="/MainAssignment3/doSearch" method="POST" commandName="p">


<c:forEach var="p" items='${foundPersons}' varStatus="status">

<td>${p.name}</td>
<td>${p.address}</td>
<td>${p.gender}</td>
<td>${p.salary}</td>

</c:forEach>


</springForm:form>
</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 uri="http://www.springframework.org/tags/form"
    prefix="springForm"%>
<%@ 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 Person</title>
</head>
<body>
<h1>Employee Registration Form</h1>


    <springForm:form action="/MainAssignment3/save" method="POST"
        commandName="person">

        <table style="border: thin; border: ridge;">

            <tr>
                <td>Enter Name:</td>
                <td bordercolor="#FF0000" ><springForm:input path="name" 
                        placeholder="Enter Name" /></td>

                <td><springForm:errors path="name" /></td>

            </tr>
            <tr>
                <td>Enter address:</td>
                <td><input type="text" name="address" placeholder="Enter Address" ></td>
                <td><springForm:errors path="address" /></td>
            </tr>
            <tr>
                <td>Enter gender:</td>
                <td><springForm:input path="gender" id="gender" placeholder="Enter Gender" /></td>
                <%-- <td><springForm:errors path="gender" /></td> --%>
            </tr>
            <tr>
                <td>Enter salary:</td>
                <td><input type="text" name="salary" placeholder="Enter Salary"  ></td>
                <td><springForm:errors path="salary" /></td>            
                <td style="padding-left: 110px;"></td>

            </tr>
            <tr>
            <td><input type="submit"value="submit"></td>
            </tr>

        </table>
    </springForm:form>
</body>
</html>

///////////////////////////////////// updatePerson.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 uri="http://www.springframework.org/tags/form"
    prefix="springForm"%>
<%@ 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>Update Person</title>
</head>
<body>



    <springForm:form action="/MainAssignment3/update" method="POST" commandName="person">

        <table style="border: thin; border: ridge;">        
        <tr>
            <td><input type="hidden" name="id" value="${id}"></td>

            </tr>
            <tr>
                <td>Enter Name:</td>
                <td bordercolor="#FF0000" >
                <springForm:input path="name" placeholder="Enter Name"  value='${name}'/></td>

            <%--    <td><springForm:errors path="name" /></td> --%>

            </tr>
            <tr>
                <td>Enter address:</td>
                <td><springForm:input path="address" id="address"  placeholder="Enter Address" value='${address}'/></td> 
            <%--    <td><springForm:errors path='${p1.address}'/></td> --%>
            </tr>
            <tr>
                <td>Enter gender:</td>
                <td><springForm:input path="gender" id="gender"  placeholder="Enter Gender" value='${gender}' /></td>
                <%-- <td><springForm:errors path='${p1.gender}'/></td> --%>
            </tr>
            <tr>
                <td>Enter salary:</td>
                <td><springForm:input path="salary" id="salary"  placeholder="Enter Salary"  value='${salary}'/></td>
            <%--    <td><springForm:errors path='${p1.salary}' /></td> --%>         
                <td style="padding-left: 110px;"></td>

            </tr>
            <tr>
            <td><input type="submit"value="submit"></td>
            </tr>

        </table>
    </springForm:form>

</body>
</html>