【问题标题】:Inserting a row into a database using hibernate, I'm getting "1" and null put into the database instead of user inputted values使用休眠将一行插入数据库,我将“1”和空值放入数据库而不是用户输入的值
【发布时间】:2020-12-27 18:05:32
【问题描述】:

我正在尝试使用休眠和会话/会话工厂向数据库添加一行。但是,当我执行以下代码时,它只添加到数据库一次,值为“1,null”。我认为问题出在 ProductAdd.java(如下)中,但我不确定。

package com.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.product.Product;
import com.utility.HibernateUtility;



@WebServlet("/ProductAdd")
public class ProductAdd extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("inside servlet");
         
        Product product= new Product(request.getParameter("prodId"),request.getParameter("prodName"));
         

        try {
            
            
            
             Product p = new Product();
             p.setName(product.getName());
             p.setId(product.getName());
             Session session = HibernateUtility.getSessionFactory().openSession();

             org.hibernate.Transaction transaction = null;
             
             try {
      
                 transaction = session.beginTransaction();
                 String sql = "INSERT INTO Product VALUES (:idVal, :nameVal)";
      
                 Query query = session.createSQLQuery(sql);
                  
                 query.setParameter("idVal", product.getId());
                 query.setParameter("nameVal", product.getName());
                 
                 query.executeUpdate();
                  
                 session.getTransaction().commit();
                  
             } catch (HibernateException e) {
                 transaction.rollback();
                 e.printStackTrace();
              
             } finally {
                 session.close();
             }
         
            
            System.out.println(("Product is added."));

        } catch (Exception e) {
            // TODO: handle exception
        }
        HttpSession session= request.getSession();
    
        session.setAttribute("sesname", request.getParameter("prodId"));
    
        response.sendRedirect("addsuccess.jsp");
    

    }

}

如果需要,这里是我的 Product.java:

package com.product;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Product implements Serializable{

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String id;
    private String name;

    public Product(String string, String string2) {
        super();
        // TODO Auto-generated constructor stub
    }
    public Product() {
        // TODO Auto-generated constructor stub
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}

我也有我的 HibernateUtility 类:

package com.utility;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtility {
                private static final SessionFactory sessionFactory = createSessionFactory();

                public static SessionFactory createSessionFactory() {
                                try {
                                      return new AnnotationConfiguration().configure().buildSessionFactory();
                                } catch (Exception ex) {
                                                System.err.println("SessionFactory creation failed");
                                                throw new ExceptionInInitializerError(ex);
                                }
                }

                /**
                 * @return the sessionfactory
                 */
                public static SessionFactory getSessionFactory() {
                                return sessionFactory;
                }

}

连同hibernate.cfg.xml。

【问题讨论】:

    标签: java hibernate servlets


    【解决方案1】:

    您实际上并未使用请求参数,因为您的产品构造函数如下所示:

    public Product(String string, String string2) {
        super();
        // TODO Auto-generated constructor stub
    }
    

    所以这条线并没有达到你的预期:

    Product product= new Product(request.getParameter("prodId"),request.getParameter("prodName"));
    

    这些也没有:

    Product p = new Product();
    p.setName(product.getName());
    p.setId(product.getName());
    

    或者这些:

    query.setParameter("idVal", product.getId());
    query.setParameter("nameVal", product.getName());
    

    (顺便说一句,如果你仍然使用product来设置查询参数,不知道p有什么用)。

    因此,由于GenerationType.AUTO,因此产品名称最终为 null,id 为 1,否则我认为这也是 null。

    你需要改变你的构造函数来使用参数:

    public Product(String string, String string2) {
        this.id = string;
        this.name = string2;
    }
    

    这样,您稍后将有一些东西要发送到您的数据库查询。

    【讨论】:

    • 那么,我应该怎么做才能让用户输入到数据库中呢?我删除了一些未使用的代码,例如 Person() p;..
    • 你的构造函数什么都不做。您需要将其更改为带有参数的构造函数。请参阅我对答案的更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 2019-04-29
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    相关资源
    最近更新 更多