简体   繁体   中英

Inserting a row into a database using hibernate, I'm getting “1” and null put into the database instead of user inputted values

I am trying to add a row to the database using hibernate and sessions/sessionfactory. However when I did the following code, it only added to the database once with values of "1, null". I think the problem is within ProductAdd.java (below), but I am not sure.

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");
    

    }

}

Here is my Product.java if needed also:

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

I also have my HibernateUtility class:

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

}

Along with hibernate.cfg.xml.

You are not actually using the request parameters because your product constructor looks like this:

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

So this line doesn't do what you expect:

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

And neither do these:

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

or these:

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

(by the way, not sure what is the use of p if you still use product to set the query params).

So you end up with null for the product name, and 1 for the id because of the GenerationType.AUTO , otherwise that would have been null too, I think.

You need to change your constructor to use the parameters:

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

This way, you will later have something to send to your database query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM