在Hibernate + Spring MVC中编辑不能在CRUD中工作

时间:2016-08-11 06:39:28

标签: hibernate spring-mvc

我正在开发一个spring mvc + hibernate CRUD应用程序。

我的创建,添加和删除功能正常工作,但是当我使用主页上的编辑功能时,表单不会被填充以进行编辑。

自动生成ID。

我的代码:

////////////////////////////////Controller//////////////////////////////
@Controller
public class MainController {
    @Autowired 
    private PersonService ps;

    @RequestMapping("/updatePerson")
    public String updatePerson(HttpServletRequest req,@ModelAttribute Person p)
    {
        int id = Integer.parseInt(req.getParameter("id"));
        ps.updatePerson(p);
        return "redirect:http://localhost:8080/MainAssignment3/AddPerson";
    }
}

////////////////////////////DAOImpl///////////////////////
public void updatePerson(Person p) {
    Session session = new Configuration().configure().buildSessionFactory().openSession();
    Person p1 = (Person) session.load(Person.class, new Integer(p.getId()));
    //Person person = session.get(Person.class, p.getId());
    p.setAddress(p.getAddress());
    p.setGender(p.getGender());
    p.setSalary(p.getSalary());
    p.setName(p.getName()); // modify the loaded object somehow
    session.saveOrUpdate(p);
    //Transaction t = session.beginTransaction();
    //Query query = session.createQuery("from Person");
    //t.commit();
    session.close();
}


/////////////////////////////////////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>${status.index+1}</td>
                    <td>${person.id}</td>
                    <td>${person.address}</td>
                    <td>${person.gender}</td>
                    <td>${person.salary}</td>
                    <td>${person.name}</td>
                    <td>
                        <a href="/MainAssignment3/updatePerson?id=${person.id}">Edit</a>
                        <a href="/MainAssignment3/remove/{id}?id=${person.id}">Delete</a>
                    </td>
                </tr>
            </c:forEach> 
        </table>
    </body>
</html>

/////////////////////////////////Configuration//////////////////////
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.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
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.service.PersonService;
import com.service.PersonServiceImpl;

@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.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("/resource/**").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;
    }  
}

///////////////////////////Person.class////////////////////////////
@Entity
//@Table(name="person")
public class Person {
    @Id 

    @GeneratedValue(strategy=GenerationType.AUTO)

    @Column(name = "id")

    private Integer id;
    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")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

1 个答案:

答案 0 :(得分:1)

您的例外情况:Could not locate hibernate.cfg.xml

您应该将hibernate.cfg.xml放在 WEB-INF/src 目录下。

<强>更新

在您的代码中,您使用注释配置了以下详细信息,但您错过了提及 Mapping class Person.class<beans:property name="annotatedClasses">)。

<beans:bean id="hibernate4AnnotatedSessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource" />
        <beans:property name="annotatedClasses">
            <beans:list>
                <beans:value>spring.model.Person</beans:value>
            </beans:list>
        </beans:property>
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
                </beans:prop>
                <beans:prop key="hibernate.show_sql">true</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean>

使用注释:

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;
    }