如何使用 hibernate 和 springMVC 将数据插入数据库

How can I insert data into a database by using hibernate and springMVC

您好,我尝试使用 spring mvc 将数据添加到 oraclexe 数据库,并通过 dao 设计模式休眠,但它会出现此错误 "org.springframework.web.util.NestedServletException" 如何解决这个问题?

这个程序只适用于没有休眠的 springMVC 但是当我尝试添加休眠时它不起作用并给我错误我不知道如何连接 springMVC 与休眠

这是我的pom.xml

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc14</artifactId>
      <version>10.2.0.4.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.4.1.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-annotations</artifactId>
        <version>3.5.6-Final</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.5</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>

  </dependencies>

和classResource.java

package com.spring.mvc.model;

import javax.persistence.*;

@Entity
@Table(name = "RESOURCSE")
public class Resource {
    @Id
    @GeneratedValue
    @Column(name = "ID",unique = true,length = 10)
    private int id;
    @Column(name = "NAME", length = 25)
    private String name;
    @Column(name = "TYPE", length = 30)
    private String type;
    @Column(name = "unitOfMesure", length = 25)
    private String unitOfMesure;
    @Column(name = "notes", length = 25)
    private String notes;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }

    public Resource(String name, String type, String unitOfMesure, String notes) {
        this.name = name;
        this.type = type;
        this.unitOfMesure = unitOfMesure;
        this.notes = notes;
    }

    public String getUnitOfMesure() {
        return unitOfMesure;
    }

    public void setUnitOfMesure(String unitOfMesure) {
        this.unitOfMesure = unitOfMesure;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Resource() {
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Resource{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", type='" + type + '\'' +
                ", unitOfMesure='" + unitOfMesure + '\'' +
                ", notes='" + notes + '\'' +
                '}';
    }
}

和ResourceDaoImpl

package com.spring.mvc.dao;

import com.spring.mvc.model.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Repository
@Transactional
public class ResourceDaoImpl implements ResourceDao {



    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void addResource(Resource resource) {
        try (Session session = this.sessionFactory.getCurrentSession()) {
            session.persist(resource);
        }

    }

    @Override
    public void updateResource(Resource resource) {
        Session session = this.sessionFactory.getCurrentSession();
        session.update(resource);

    }

    @Override
    public List<Resource> listResource() {
        Session session = this.sessionFactory.getCurrentSession();
        List list_resources = session.createQuery("from Resource ").list();
        return list_resources;
    }

    @Override
    public Resource getResourceById(int id) {
        Session session = this.sessionFactory.getCurrentSession();
        Resource resourceId = session.load(Resource.class, id);
        return resourceId;
    }

    @Override
    public void removeResource(int id) {
        Session session = this.sessionFactory.getCurrentSession();
        Resource resourceId = session.load(Resource.class, id);
        if (resourceId != null){
            session.delete(resourceId);
        }

    }
}

和 ResourceServiceImpl

package com.spring.mvc.service;

import com.spring.mvc.dao.ResourceDao;
import com.spring.mvc.model.Resource;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@Transactional
public class ResourceServiceImpl implements ResourceService {


    private ResourceDao resourceDao;

    public ResourceDao getResourceDao() {
        return resourceDao;
    }

    public void setResourceDao(ResourceDao resourceDao) {
        this.resourceDao = resourceDao;
    }

    @Override
    public void addResource(Resource resource) {
        this.resourceDao.addResource(resource);

    }

    @Override
    public void updateResource(Resource resource) {
        this.resourceDao.updateResource(resource);

    }

    @Override
    public List<Resource> listResource() {
        return this.resourceDao.listResource();
    }

    @Override
    public Resource getResourceById(int id) {
        return this.resourceDao.getResourceById(id);
    }

    @Override
    public void removeResource(int id) {

        this.resourceDao.removeResource(id);
    }
}

和资源控制器

package com.spring.mvc.controller;

import com.spring.mvc.model.Resource;
import com.spring.mvc.service.ResourceService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@Controller
@RequestMapping("/resource")
public class ResourceController {
    private ResourceService resourceService;

    public void setResourceService(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model){
        return "resource_add";
    }

    @ModelAttribute("resource")
    public Resource resource(){
        return new Resource();
    }

    @ModelAttribute("typeOptions")
    public List<String> getTypes(){
        return new LinkedList<>(Arrays.asList(new String[]{
                "English","France","Italy"
        }));
    }

    @ModelAttribute("radioOptions")
    public List<String> getRadios(){
        return new LinkedList<>(Arrays.asList(new String[]{
                "Hour","Piece","Tones"
        }));
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@ModelAttribute Resource resource){

        this.resourceService.addResource(resource);
        System.out.println(resource);
        return "resource_add";
    }
}

这是我的 hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/xsd/hibernate-configuration">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
        <property name="connection.username">username</property>
        <property name="connection.password">password</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</property>
        <mapping class="com.spring.mvc.model.Resource"></mapping>
    </session-factory>
</hibernate-configuration>

First do not put @Transactional in front of DAO classes, put it only above the Services classes.it won't be an error but it is a good practice

编辑 您没有在 spring-mvc 中添加休眠,这就是 @Autowired 不起作用的原因。您需要像这样 spring 添加休眠配置 (这是一个示例代码,并更改您适当的值)

 <!-- Add support for component scanning -->
    <context:component-scan base-package="net.javaguides.springmvc" />
    <!-- Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven />
    <!-- Define Spring MVC view resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- Step 1: Define Database DataSource / connection pool -->
    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=false&amp;serverTimezone=UTC" />
        <property name="user" value="user" />
        <property name="password" value="password" />   
    </bean>
    <!-- Step 2: Setup Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="net.javaguides.springmvc.entity" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <!-- Step 3: Setup Hibernate transaction manager -->
    <bean id="myTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <!-- Step 4: Enable configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="myTransactionManager" />
    <!-- Add support for reading web resources: css, images, js, etc ... -->
    <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

/********************************************* ***************************/

在这个方法中

@Override
public void updateResource(Resource resource) {
    Session session = this.sessionFactory.getCurrentSession();
    session.update(resource);

}

像这样使用 beginTransaction 并提交

@Override
public void updateResource(Resource resource) {
    Session session = this.sessionFactory.getCurrentSession();
    session.beginTransaction();
    session.update(resource);
    session.getTransaction().commit();

}

我不确定你在这里初始化了 sessionFactory

private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
    return sessionFactory;
}

您可以简单地使用 @Autowired 注释进行初始化。就这样,

@Autowired
protected SessionFactory sessionFactory;