Java Hibernate框架在数据库中保存记录

Java Hibernate框架在数据库中保存记录,java,spring,hibernate,Java,Spring,Hibernate,我开始使用Hibernate框架。我试图在数据库中保存一些记录。在保存时,我遇到了这个错误。在解决这个问题时需要专家评审 错误:所需的Expanditure参数“Expanditure”不存在 我不知道怎么解决这个问题。若我从控制器类中删除这些参数,则字段变为空,若将这些expanditure参数放入,则返回错误 这里是实体类 package com.bvas.insight.entity; /** * * @author shoaib */ import java.io.Serial

我开始使用Hibernate框架。我试图在数据库中保存一些记录。在保存时,我遇到了这个错误。在解决这个问题时需要专家评审

错误:所需的Expanditure参数“Expanditure”不存在

我不知道怎么解决这个问题。若我从控制器类中删除这些参数,则字段变为空,若将这些expanditure参数放入,则返回错误

这里是实体类

package com.bvas.insight.entity;

/**
 *
 * @author shoaib
 */

import java.io.Serializable;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import javax.persistence.Basic;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@Table(name = "expanditure")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Expanditure.findAll", query = "SELECT e FROM Expanditure e"),
    @NamedQuery(name = "Expanditure.findById", query = "SELECT e FROM Expanditure e WHERE e.id = :id"),
    @NamedQuery(name = "Expanditure.findByRoute", query = "SELECT e FROM Expanditure e WHERE e.route = :route"),
    @NamedQuery(name = "Expanditure.findByMonth", query = "SELECT e FROM Expanditure e WHERE e.month = :month"),
    @NamedQuery(name = "Expanditure.findByYear", query = "SELECT e FROM Expanditure e WHERE e.year = :year"),
    @NamedQuery(name = "Expanditure.findByAmount", query = "SELECT e FROM Expanditure e WHERE e.amount = :amount"),
    @NamedQuery(name = "Expanditure.findByDescription", query = "SELECT e FROM Expanditure e WHERE e.description = :description"),
    @NamedQuery(name = "Expanditure.findByMonthAndYear", query = "SELECT e FROM Expanditure e WHERE e.year = :year and e.month = :month ")
})
public class Expanditure implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
 // @GeneratedValue(strategy = GenerationType.IDENTITY)
    @GeneratedValue(strategy=GenerationType.AUTO)
//    @Basic(optional = false)
    @Column(name = "Id")
    private Integer id;
//    @Basic(optional = false)
  //  @NotNull
 //   @Size(min = 1, max = 45)
    @Column(name = "Route")
    private String route;
//    @Basic(optional = false)
//    @NotNull
//    @Size(min = 1, max = 10)
    @Column(name = "Month")
    private String month;
 //   @Basic(optional = false)
   // @NotNull
  //  @Size(min = 1, max = 4)
    @Column(name = "Year")
    private String year;
 //   @Basic(optional = false)
 //   @NotNull
    @Column(name = "Amount")
    private Double amount;
 //   @Basic(optional = false)
 //   @NotNull
 //   @Size(min = 1, max = 200)
    @Column(name = "Description")
    private String description;

    public Expanditure() {
    }

    public Expanditure(Integer id) {
        this.id = id;
    }

    public Expanditure(Integer id, String route, String month, String year, double amount, String description) {
        this.id = id;
        this.route = route;
        this.month = month;
        this.year = year;
        this.amount = amount;
        this.description = description;
    }

    public Integer getId() {
        return id;
    }

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

    public String getRoute() {
        return route;
    }

    public void setRoute(String route) {
        this.route = route;
    }

    public String getMonth() {
        return month;
    }

    public void setMonth(String month) {
        this.month = month;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Expanditure)) {
            return false;
        }
        Expanditure other = (Expanditure) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.test.Expanditure[ id=" + id + " ]";
    }

}
控制器类

@RequestMapping(value = "/Expanditure", method = RequestMethod.POST)
public ModelAndView addExpanditure(Model map, HttpSession session,ModelAndView mav, @RequestParam("Expanditure")Expanditure expanditure)
{
    expanditure = reportService.SaveExpanditure(expanditure);
    mav.clear();
    mav.setViewName("expanditurepage");
    mav.addObject("user", user);
    mav.addObject("branch", branch);
    mav.addObject("appcss", appcss);
    mav.addObject("sysdate", InsightUtils.getNewUSDate());
    return mav;

} 
服务等级

public Expanditure SaveExpanditure(Expanditure expanditure) {

      Session session = null;


       try {
            session = sessionFactory.getCurrentSession();
            session.getTransaction().begin();
            session.save(expanditure);
        } catch (Exception e) {
            expanditure = null;
        } finally {
           session.getTransaction().commit();
            session.close();
        } 


        return expanditure; 
    }  
JSP页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html lang="en" manifest="/not-existing.appcache">
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
<!--<![endif]-->

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix='c'%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<head>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">


<link type="text/css" rel="stylesheet"
    href="${pageContext.request.contextPath}/${appcss}" />


<title>Utilities</title>
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

<style type="text/css">
/* label color */
.input-field label {
    color: #00b0ff;
}
/* label focus color */
.input-field input[type=text]:focus+label {
    color: #00b0ff;
}
/* label underline focus color */
.input-field input[type=text]:focus {
    border-bottom: 1px solid #00b0ff;
    box-shadow: 0 1px 0 0 #00b0ff;
}
/* valid color */
.input-field input[type=text].valid {
    border-bottom: 1px solid #00b0ff;
    box-shadow: 0 1px 0 0 #00b0ff;
}
/* invalid color */
.input-field input[type=text].invalid {
    border-bottom: 1px solid #00b0ff;
    box-shadow: 0 1px 0 0 #00b0ff;
}
/* icon prefix focus color */
.input-field .prefix.active {
    color: #00b0ff;
}
</style>
<script type="text/javascript">
    var datefield = document.createElement("input")
    datefield.setAttribute("type", "date")
    if (datefield.type != "date") { //if browser doesn't support input type="date", load files for jQuery UI Date Picker
        document
                .write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
        document
                .write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
        document
                .write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
    }
</script>
<c:choose>
    <c:when test="${branch == 'CHS'}">
        <c:set value="#4682B4" var="bg"></c:set>
    </c:when>
    <c:when test="${branch == 'GRS'}">
        <c:set value="#5971AD" var="bg"></c:set>
    </c:when>
    <c:when test="${branch == 'AMS'}">
        <c:set value="#4A777A" var="bg"></c:set>
    </c:when>
    <c:when test="${branch == 'NYS'}">
        <c:set value="#5971AD" var="bg"></c:set>
    </c:when>
    <c:when test="${branch == 'MPS'}">
        <c:set value="#8d96cd" var="bg"></c:set>
    </c:when>
    <c:otherwise>
        <c:set value="#000000" var="bg"></c:set>
    </c:otherwise>
</c:choose>
</head>
<body bgcolor="#f4f6f8"
    style="word-wrap: break-word; white-space: normal; font-size: 0.7em;">
    <!-- START HEADER -->
    <header id="header" class="page-topbar">
        <!-- start header nav-->
        <div class="navbar-fixed">
            <form class="col s12" role="navigation" method="post" id="navform"
                name="navform" action="/insight/nav">
                <input type="hidden" id="navmode" name="navmode" value="logout">
                <nav class="navbar-color">
                    <div class="nav-wrapper">
                        <a href="#" class="brand-logo right">&nbsp;${branch}</a>
                        <ul class="left hide-on-med-and-down">
                            <li class="active"><a id="navhome" href="#">Home</a></li>
                            <li class="dropdown"><a href="#" class="dropdown-toggle"
                                data-toggle="dropdown">Status <b class="caret"></b></a>
                                <ul class="dropdown-menu">
                                </ul></li>
                            <li><a id="User:" href="#">${user.username}</a></li>
                            <li><a id="Date:" href="#">${sysdate}</a></li>
                            <li class="active"><a id="navlogout" href="#">Logout</a></li>
                            <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</li>
                            <li></li>
                        </ul>
                    </div>
                </nav>
            </form>
        </div>
    </header>
    <!-- END HEADER -->
    <div class="row">
        <div class="row">
            <form class="col s12" role="form" method="post" id="Expanditureform"
                name="Expanditureform" action="/insight/report/Expanditure">
                <div class="row">
                    <h5 class="light col s12">Expenditures</h5>
                </div>
                <div class="card light-blue lighten-5">
                <div class="card-content">


                    <div class="row">

                                            <div class="input-field col s2">
                            <input style="font-weight: bold;" id="route" name="route"
                                value="${expanditure.route}" type="text"><label for="route"><strong>Route
                                    </strong></label>
                        </div>


                        <div class="input-field col s2">
                            <input style="font-weight: bold;" id="month" name="month"
                                value="${expanditure.month}" type="text"><label for="Month"><strong>Month
                                    </strong></label>
                        </div>


                        <div class="input-field col s2">
                            <input style="font-weight: bold;" id="year"
                                name="year" value="${expanditure.year}" type="text"><label
                                for="year"><strong>Year</strong></label>
                        </div>



                        <div class="input-field col s2">
                            <input style="font-weight: bold;" id="amount" name="Amount"
                                value="${expanditure.amount}" type="text"><label for="Amount"><strong>Amount</strong></label>
                                                </div>
                        <div class="input-field col s12">
                            <textarea id="Description" name="Description"
                                class="materialize-textarea" maxlength="250">${expanditure.description}</textarea>
                            <label for="Description"><strong>Description</strong></label>
                        </div>


                                                        <div class="col s2">
                                    <button
                                        class="btn-floating btn-large waves-effect waves-light  blue"
                                        type="submit" id="expanditureBtn"
                                        name="expanditureBtn" value="expanditureBtn">
                                        <i class="mdi-content-add-circle-outline right"></i>
                                    </button>
                                                       </div>

                        </div>



    </div>
</div>
                        </form>
                </div>
                </div>
    <script src="<c:url value="/resources/jquery/jquery-2.1.3.js" />"></script>
    <script src="<c:url value="/resources/jquery/materialize.js" />"></script>

    <script>
        $(document).ready(function() {

            var cb = '<c:out value="${bg}"/>';
            $('nav').css('background-color', cb);


            $(".button-collapse").sideNav();
            $(".dropdown-button").dropdown();
            $('select').material_select();

            $('.collapsible').collapsible({
                accordion : true
            // A setting that changes the collapsible behavior to expandable instead of the default accordion style
            });

            if (datefield.type != "date") { //if browser doesn't support input type="date", initialize date picker widget:
                jQuery(function($) { //on document.ready
                    $('#analyticsfromdate').datepicker();
                    $('#analyticstodate').datepicker();
                })
            }

            $("#navlogout").click(function() {
                $('input[name=navmode]').val('logout');
                $("#navform").submit();
            });

            $("#navhome").click(function() {
                $('input[name=navmode]').val('home');
                $("#navform").submit();
            });

            $("#expanditureBtn").click(function() {
                $("#expanditureform")
                .attr("action",
                        "/insight/report/Expanditure");
                    $("html, body").animate({
                        scrollTop : 0
                    }, "fast");
                    $("#expanditureform")
                            .submit();
            });


                            $("#expanditureBtn")
                            .click(
                                    function() {
                                        $("#expanditureform")
                                                .attr("action",
                                                        "/insight/report/Expanditure");
                                        $("#expanditurform")
                                                .submit();
                                    });


        });
    </script>
</body>
</html>

公用事业
/*标签颜色*/
.输入字段标签{
颜色:#00b0ff;
}
/*标签焦点颜色*/
.输入字段输入[类型=文本]:焦点+标签{
颜色:#00b0ff;
}
/*标签下划线焦点颜色*/
.输入字段输入[类型=文本]:焦点{
边框底部:1px实心#00b0ff;
盒影:0 1px 0 0#00b0ff;
}
/*有效颜色*/
.input字段输入[type=text]。有效{
边框底部:1px实心#00b0ff;
盒影:0 1px 0 0#00b0ff;
}
/*无效颜色*/
.input字段输入[type=text]。无效{
边框底部:1px实心#00b0ff;
盒影:0 1px 0 0#00b0ff;
}
/*图标前缀焦点颜色*/
.输入字段.前缀.active{
颜色:#00b0ff;
}
var datefield=document.createElement(“输入”)
datefield.setAttribute(“类型”、“日期”)
如果(datefield.type!=“date”){//如果浏览器不支持输入type=“date”,则加载jQuery UI日期选择器的文件
文件
.write(“\n”)
文件
.write(“\n”)
文件
.write(“\n”)
}
支出 路线 年度 金额 ${expanditure.description} 说明 $(文档).ready(函数(){ var cb=“”; $('nav').css('background-color',cb); $(“.button collapse”).sideNav(); $(“.dropdown按钮”).dropdown(); $('select')。材料选择(); $('.collable')。可折叠({ 手风琴:真的吗 //将可折叠行为更改为可展开而不是默认手风琴样式的设置 }); 如果(datefield.type!=“date”){//如果浏览器不支持输入type=“date”,则初始化日期选择器小部件: jQuery(函数($){//on document.ready $(“#analyticsfromdate”).datepicker(); $('#analyticstodate').datepicker(); }) } $(“#navlogout”)。单击(函数(){ $('input[name=navmode]').val('logout'); $(“#navform”).submit(); }); $(“#导航主页”)。单击(函数(){ $('input[name=navmode]').val('home'); $(“#navform”).submit(); }); $(“#expanditureBtn”)。单击(函数(){ 美元(“#改革”) .attr(“操作”, “/insight/report/Expanditure”); $(“html,body”).animate({ 滚动顶部:0 }“快”); 美元(“#改革”) .submit(); }); $(“#expanditureBtn”) .点击( 函数(){ 美元(“#改革”) .attr(“操作”, “/insight/report/Expanditure”); $(“#扩展格式”) .submit(); }); });
这只是一个提示,我认为您的控制器类中缺少expanditure参数,当您对url“/expanditure”发出请求时,

您会收到此错误,因为您没有发送任何名为“expanditure”的请求参数。在这里,您的程序希望通过请求参数“Expanditure”获得一些值

相反,您可以将控制器定义为:

@RequestMapping(value = "/Expanditure", method = RequestMethod.POST)
public ModelAndView addExpanditure(Model map, HttpSession session,ModelAndView mav, 
                                   @RequestParam("route")Expanditure route, 
                                   @RequestParam("month")Expanditure month, 
                                   @RequestParam("year")Expanditure year, 
                                   @RequestParam("amount")Expanditure amount, 
                                   @RequestParam("Description")Expanditure Description)
{
    ..
    ..
    ..
}