2016-11-19 70 views
0

我正在使用struts2和hibernate集成,通過以下鏈接http://www.tutorials4u.net/struts2-tutorial/struts2_crud_example.html嘗試更新記錄,但不是更新它插入新記錄,我在發佈之前看到了所有hibernate更新問題這個職位,但他們沒有爲我工作,所以請我請求將其標記爲重複前閱讀我的問題,因爲我已經嘗試了很多從已經發布的問題和答案...HIbernate saveorUpdate()在更新時插入新記錄

AddStudentAction.java

public class AddStudentAction extends ActionSupport implements 
     ModelDriven<Student> { 

    public AddStudentAction() { 
     // TODO Auto-generated constructor stub 
    } 

    Student student = new Student(); 

    private String firstName; 

    private int id; 

    public int getId() { 
     return id; 
    } 

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

    public String getFirstName() { 
     return firstName; 
    } 

    public void setFirstNameSearch(String firstName) { 
     this.firstName = firstName; 
    } 

    List<Student> students = new ArrayList<Student>(); 

    List<Student> studentFirstNames = new ArrayList<Student>(); 

    public List<Student> getStudentFirstNames() { 
     return studentFirstNames; 
    } 

    public void setStudentFirstNames(List<Student> studentFirstNames) { 
     this.studentFirstNames = studentFirstNames; 
    } 

    StudentDAO dao = new StudentDAO(); 

    public Student getStudent() { 
     return student; 
    } 

    public void setStudent(Student student) { 
     this.student = student; 
    } 

    public List<Student> getStudents() { 
     return students; 
    } 

    public void setStudents(List<Student> students) { 
     this.students = students; 
    } 

    public StudentDAO getDao() { 
     return dao; 
    } 

    public void setDao(StudentDAO dao) { 
     this.dao = dao; 
    } 

    @Override 
    public Student getModel() { 
     // TODO Auto-generated method stub 
     return student; 
    } 
@Override 
public String execute() { 
    // TODO Auto-generated method stub 
    dao.addStudent(student); 
    String f = student.getFirstName(); 
    String l = student.getLastName(); 
    int m = student.getMarks(); 
    System.out.println(f + l + m + "Inside execute method"); 
    return "success"; 
} 

public String updateStudent() { 

    dao.addStudent(student); 
    return "success"; 
} 

public String listStudents() { 
    students = dao.getStudents(); 
    return "success"; 
} 
public String editStudent() { 
    HttpServletRequest request = (HttpServletRequest) ActionContext 
      .getContext().get(ServletActionContext.HTTP_REQUEST); 
    student = dao.listStudentById(Integer.parseInt((request 
      .getParameter("id")))); 

    student.setId(Integer.parseInt((request.getParameter("id")))); 

    System.out.println(request.getParameter("id") + "id in editStudent"); 
    dao.updateStudent(student); 

    return SUCCESS; 
} 

StudentDAO.java

public class StudentDAO { 
@SessionTarget 
Session session; 

@TransactionTarget 
Transaction transaction; 
public void addStudent(Student student) { 
    try { 
     session.saveOrUpdate(student); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

public void updateStudent(Student student) { 
    try { 

     session.saveOrUpdate(student); 
     session.flush(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
public Student listStudentById(int Id) { 
    Student student = null; 
    try { 
     student = (Student) session.get(Student.class, Id); 
    } catch (Exception e) { 

    } 
    return student; 
} 

}

Student.java

package com.struts2hibernatepagination.hibernate; 

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

@Entity 
@Table(name = "student") 
public class Student { 

    @Id 
    @GeneratedValue 
    @Column(name = "id") 
    private int id; 
    @Column(name = "last_name") 
    private String lastName; 
    @Column(name = "first_name") 
    private String firstName; 
    private int marks; 

    public int getId() { 
     return id; 
    } 

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

    public String getLastName() { 
     return lastName; 
    } 

    public void setLastName(String lastName) { 
     this.lastName = lastName; 
    } 

    public String getFirstName() { 
     return firstName; 
    } 

    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 

    public int getMarks() { 
     return marks; 
    } 

    public void setMarks(int marks) { 
     this.marks = marks; 
    } 

} 

struts.xml中

<?xml version="1.0" encoding="UTF-8"?> 

<package name="default" extends="hibernate-default"> 
<action name="addStudent" method="execute" 
     class="com.struts2hibernatepagination.action.AddStudentAction"> 
     <interceptor-ref name="defaultStackHibernateStrutsValidation"> 
      <param name="validation.excludeMethods">listStudents</param> 
      <param name="validation.excludeMethods">fetchStudentList</param> 
     </interceptor-ref> 
     <result name="success" type="redirect"> 
      listStudents 
     </result> 
     <result name="input">/student.jsp</result> 
    </action> 
<action name="editStudent" 
     class="com.struts2hibernatepagination.action.AddStudentAction" 
     method="editStudent"> 
     <interceptor-ref name="basicStackHibernate" /> 
     <result name="success">/student.jsp</result> 
    </action> 
</package> 

的hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE hibernate-configuration PUBLIC 
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 
<hibernate-configuration> 
    <session-factory> 
     <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> 
     <property name="hibernate.connection.password">admin12345</property> 
     <property name="hibernate.connection.url">jdbc:mysql://192.168.1.3:3306/nupur</property> 
     <property name="hibernate.connection.username">root</property> 
     <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 
     <property name="show_sql">true</property> 
     <property name="hibernate.hbm2ddl.auto">update</property> 
     <mapping class="com.struts2hibernatepagination.hibernate.Student" /> 
    </session-factory> 
</hibernate-configuration> 

student.jsp

<%@ page contentType="text/html; charset=UTF-8"%> 
<%@ taglib prefix="s" uri="/struts-tags"%> 

<html> 
<head> 
<title>Hello World</title> 
<s:head /> 
</head> 
<body> 
    <a href="searchStudent.jsp">Search</a> 
    <s:form action="addStudent"> 
     <s:actionerror /> 
     <s:textfield name="firstName" label="First Name" /> 
     <s:textfield name="lastName" label="Last Name" /> 
     <s:textfield name="marks" label="Marks" /> 
     <s:submit value="Save" /> 
     <hr /> 
     <table border="2"> 
      <tr bgcolor="cyan"> 
       <th><u>First Name</u></th> 
       <th><u>Last Name</u></th> 
       <th><u>Marks</u></th> 
       <th><u>Edit</u></th> 
       <th><u>Delete</u></th> 
      </tr> 
      <s:iterator value="students"> 
       <tr> 
        <td><s:property value="firstName" /></td> 
        <td><s:property value="lastName" /></td> 
        <td><s:property value="marks" /></td> 
        <td><s:url id="editURL" action="editStudent"> 
          <s:param name="id" value="%{id}"></s:param> 
         </s:url> <s:a href="%{editURL}">Edit</s:a></td> 
        <td><s:url id="deleteURL" action="deleteStudent"> 
          <s:param name="id" value="%{id}"></s:param> 
         </s:url> <s:a href="%{deleteURL}">Delete</s:a></td> 
       </tr> 
      </s:iterator> 
     </table> 

    </s:form> 

    <s:form action="fetchStudentList"> 
     <s:submit value="Show"></s:submit> 

    </s:form> 


</body> 
</html> 

請幫我......因爲我嘗試了所有辦法無論是使用調用Session.flush()或刪除@GeneratedValue註釋

標識在傳遞addStudent()

public String editStudent() { 
HttpServletRequest request = (HttpServletRequest) ActionContext 
         .getContext().get(ServletActionContext.HTTP_REQUEST); 
       dao.listStudentById(Integer.parseInt((request.getParameter("id"))));    return SUCCESS; 
      } //AddStudetnAction class method 

                     public void addStudent(Student student) { 
       try { 
       System.out.println(student.getId() + "In DAO addStudent");// returning null 
       session.saveOrUpdate(student); 

       } catch (Exception e) { 
        e.printStackTrace(); 
       } 

    //StudentDAO class method                      

的不來的StudentDAOaddStudent()越來越nullid,如何設置id爲addStudent(),使其調用更新方法,而不是保存

回答

1

花費了近2-3天之後,我得到了解決,我在JSP中提到的<s:hidden>標籤從那裏我傳遞的id作爲 <s:hidden name="id" />,爲了更新Hibernate應該得到id,如果它沒有這樣做,它會調用保存方法。

0

,如果你想起來日期記錄你需要它的ID,SaveOrUpdate查找ID如果它在你的表中,那麼它會更新,如果它不是,那麼它添加一個新的記錄。

我不知道你如何建立你的學生,但如果你想更新你需要從數據庫中獲取的對象有ID(或者,如果你知道ID設置它),然後更新你想要什麼,而對象位於持久性上下文中並刷新。

0

這是我的編輯方法。

StudentAction。java的

public String edit() 
{ 
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST); 
    student = studentDAO.listStudentsById(Long.parseLong(request.getParameter("id"))); 

    return SUCCESS; 
} 

StudentList.jsp

<s:url id="editURL" action="edit"> 
         <s:param name="id" value="%{id}"></s:param> 
        </s:url> 
        <s:a href="%{editURL}">Edit</s:a> 
0

s:form標籤不會讓你使用任何參數的URL,但您可以使用hidden輸入字段。 s:form標記默認爲POST方法。

<s:form action="addStudent"> 
    <s:actionerror /> 
    <s:textfield name="firstName" label="First Name" /> 
    <s:textfield name="lastName" label="Last Name" /> 
    <s:textfield name="marks" label="Marks" /> 
    <s:hidden name="id"/> 
    <s:submit value="Save" /> 
    ... 
</s:form> 
+0

非常感謝先生,但我做了相同的更改並將其發佈爲前面的答案。 – Nupur

相關問題