如何更新实体休眠



我写了一个简单的java项目,可以在其中创建时间表,但我在更新Course实体时遇到了问题。我正在尝试编写一个函数,可以将讲座添加到课程中:关系OneToMany。首先,我运行.read函数从数据库中获取Lecture和Course,然后通过.getLectures((.add((,我想将我的Course类拥有的Lecture添加到Set,然后通过.update((函数,我试图更新数据库中关于课程的信息,但什么也没发生。hibernate只发出选择请求。我的代码:

Lecture lecture = lectureDao.read(lectureId);
Course course = courseDao.read(courseId);
course.getLecture().add(lecture);
courseDao.update(course);
@Override
public Course read(int id) {
transaction = currentSession().beginTransaction();
Course course = currentSession().get(Course.class, id);
currentSession().close();
return course;
}
@Override
public void update(Course course) {
if (transaction == null) {
try {
transaction = currentSession().beginTransaction();
currentSession().update(course);
currentSession().flush();
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
}
currentSession().close();
}
}

_

public class Course {
@Id
private int courseID;
private String courseName;
@OneToMany (cascade = CascadeType.ALL)
private Set<Student> students = new HashSet<>();
@OneToMany (cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private Set<Lecture> lecture = new HashSet<>();
public Course(){
super();
}
public Course(String courseName, int courseID, Set<Student> students, Set<Lecture> lecture) {
this();
this.courseName = courseName;
this.students = students;
this.courseID = courseID;
this.lecture = lecture;
}
public int getCourseID() {
return courseID;
}
public Set<Lecture> getLecture() {
return lecture;
}
public String getCourseName() {
return courseName;
}
public Set<Student> getStudents() {
return students;
}
@Override
public String toString() {
return "Course{" +
"ID=" + courseID +
", courseName='" + courseName + ''' +
'}';
}

}

public class Lecture {
@Id
private int ID;
private String lectureName;
private Date startTime;
public Lecture() {
super();
}
public Lecture(String lectureName, Date startTime, int id) {
this.lectureName = lectureName;
this.startTime = startTime;
this.ID = id;
}
public int getID() {
return ID;
}
public String getLectureName() {
return lectureName;
}

public Date getStartTime() {
return startTime;
}

很难说,因为我们没有看到实体代码。这是单向映射还是双向映射?也许你忘了@CASCADETYPE.PERSIST注释了?此外,我建议在Course.java中创建一种方法,在课程中添加新的讲座,比如

public void addNewLecture (Lecture lecture) {
If (lectureList == null){
lectureList = new ArrayList<>();
} 
this.lectureList.add(lecture);
lecture.setCourse(this);
} 

抱歉格式不正确,但我现在在安卓应用程序上

最新更新