有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法通过Hibernate更新记录

我能够通过Hibernate成功地在表中创建和插入条目,但是由于某些原因,我的更新方法似乎不起作用

对于我的表,我选择在POJO文件中使用Java注释来创建它

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

/**
 *
 * @author 
 */

@Entity
@Table(name="student") //name of DB table that will be created via Hibernate
public class Student {
   @Id //Primary Key
   @Column(name = "id") //map to column
   private Integer id;

   @Column(name = "name")
   private String name;

   @Column(name = "marks")
   private Integer marks;

   public Student(Integer id, String name, Integer marks) {
       this.id = id;
       this.name = name;
       this.marks = marks;
   }

   public Integer getId() {
       return id;
   }

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

    public String getName() {
       return name;
   }

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

   public Integer getMarks(){
       return marks;
   }

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

   @Override
   public String toString() {
       return "Student: " + this.getId() + " | " + this.getName() + " | " + this.getMarks();
   }
}

如上所述,该表是在MySQL数据库中成功创建的。但是,我无法通过HQL查询更新对象标记(等级):

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author 
 */
public class HibernateModuleTen {
    private static SessionFactory factory = new Configuration()
                                   .configure("hibernate.cfg.xml")
                                   .addAnnotatedClass(Student.class)
                                   .buildSessionFactory();
    public static void main(String[] args) {


        Session newSession = factory.getCurrentSession();

        try {

            /*Create Student Objects
              in Memory
            */
            Student student1 = new Student(100, "Greg", 95);
            Student student2 = new Student(101, "Mary", 91);
            Student student3 = new Student(102, "Sidi", 90);
            Student student4 = new Student(103, "Rokia", 92);
            Student student5 = new Student(104, "Abdel", 88);
            Student student6 = new Student(105, "Christine", 77);
            Student student7 = new Student(106, "Hamma", 90);
            Student student8 = new Student(107, "Ahmadu", 68);
            Student student9 = new Student(108, "Halimatu", 96);
            Student student10 = new Student(109, "Iziren", 99);

            //Begin transaction
            newSession.beginTransaction();
            //Save all the students
            newSession.save(student1);
            newSession.save(student2);
            newSession.save(student3);
            newSession.save(student4);
            newSession.save(student5);
            newSession.save(student6);
            newSession.save(student7);
            newSession.save(student8);
            newSession.save(student9);
            newSession.save(student10);
            newSession.getTransaction().commit();
            //Update a Student Record
            updateStudent(107, 34);

            //Delete a record if marks are less than 35 and then update Database
            deleteStudent();
            //Print all records
            newSession = factory.openSession();
            newSession.beginTransaction();
            Criteria newCriteria = newSession.createCriteria(Student.class);
            List<Student> students = newSession.createQuery("from Student").list(); //.list is .getResultList in later versions of Hibernate
            for (Student aStudent : students) {
                System.out.println(aStudent.toString());
            }
            newSession.getTransaction().commit();


        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            factory.close();
        }


    }
    public static void updateStudent(Integer id, Integer marks) throws HibernateException {
             /*Update Transaction*/
            Session newSession = factory.openSession();
            newSession.beginTransaction();
            Student studentToUpdate = (Student)newSession.get(Student.class, id); //Choose record 107 to update
            //Update the marks of Student based on ID and marks
            studentToUpdate.setMarks(marks);
            newSession.update(studentToUpdate);
            //Commit to the Transaction
            newSession.getTransaction().commit();
            newSession.close();
    }

    public static void deleteStudent() throws HibernateException {
            Session newSession = factory.openSession();
            newSession.beginTransaction();
            newSession.createQuery("delete from student s where smarks < 35")
                      .executeUpdate(); //Used for updates and deletes
            newSession.getTransaction().commit();
            newSession.close();
    }

}

update方法通过id列有效地获取表中的一条记录,并更新marks列中的元素


共 (2) 个答案

  1. # 1 楼答案

    我的删除方法存在问题:

    public static void deleteStudent() throws HibernateException {
                Session newSession = factory.openSession();
                newSession.beginTransaction();
                newSession.createQuery("delete from student s where smarks < 35")
                          .executeUpdate(); //Used for updates and deletes
                newSession.getTransaction().commit();
                newSession.close();
    }
    

    如果仔细查看查询,“从学生中删除”应该是“从学生中删除”,并带有大写字母s。粗心错误

  2. # 2 楼答案

    您没有在此处发布错误,但您的Studentbean类似乎没有在执行时调用的默认构造函数

    Student studentToUpdate = (Student)newSession.get(Student.class, id);
    

    您可以在将默认构造函数与自定义构造函数一起添加到学生类后尝试