无法通过休眠更新记录

时间:2018-06-23 02:15:14

标签: java hibernate hql

我能够通过Hibernate在表中成功创建和插入条目,但是由于某些原因,我的更新方法似乎无法正常工作。

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

no!=0 & !(no & (no - 1))

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

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

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

2 个答案:

答案 0 :(得分:0)

您没有在此处发布错误,但是看起来您的Student bean类没有默认的构造函数,在执行时会调用

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

您可以在将默认构造函数以及自定义构造函数添加到Student类之后尝试。

答案 1 :(得分:0)

我的删除方法存在问题:

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开头。粗心的错误。