子对象在一对多更新过程中未更新

时间:2017-03-10 13:39:57

标签: mysql hibernate parent-child one-to-many

因为我是hibernate的新手。以下代码是我用于使用一对多关系更新父表和子表。但是当我更新对象父表时才会获得更新。子表用于插入而不是更新。它插入并更新新记录。即使我已经为bidirectonal配置了注释。我的对象如下

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;


@Entity
@Table(name="students")

public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="student_id")
private long studentId=0;

@Column(name="sname",length=15)
private String studentName=null;

@Column(name="grp",length=15)
private String grp=null;

@OneToOne(mappedBy="parent")
private Address address; 

@OneToMany(fetch=FetchType.EAGER,targetEntity=Courses.class,cascade=CascadeType.ALL)
@JoinColumn(name="stud_id",referencedColumnName="student_id")
private Set<Courses> courses=null;

public long getStudentId() {
    return studentId;
}

public void setStudentId(long studentId) {
    this.studentId = studentId;
}

public String getStudentName() {
    return studentName;
}

public void setStudentName(String studentName) {
    this.studentName = studentName;
}

public String getGrp() {
    return grp;
}

public void setGrp(String grp) {
    this.grp = grp;
}

public Address getAddress() {
    return address;
}

public void setAddress(Address address) {
    this.address = address;
}

public Set<Courses> getCourses() {
    return courses;
}

public void setCourses(Set<Courses> courses) {
    this.courses = courses;
}
}

子对象是

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.ManyToOne;


@Entity
@Table(name="courses")
public class Courses {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="enroll_no")
private long enrollNo=0L;

@Column(name="course_id")
private long courseId=0L;

@Column(name="course_name")
private String courseName=null;

public long getCourseId() {
    return courseId;
}

public void setCourseId(long courseId) {
    this.courseId = courseId;
}

public String getCourseName() {
    return courseName;
}

public void setCourseName(String courseName) {
    this.courseName = courseName;
}
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="stud_id",referencedColumnName="student_id")
Student student=null;

public Student getStudent() {
    return student;
}

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

我曾经将数据设置为父对象和子对象以进行更新。以下代码是我更新父对象和子对象的方法。在这里,我曾经使用学生ID更新子表行。它应该按课程id更新子表行。纠正我的错误。

System.out.println("Enter the Student Id");
studentId=sc.nextLong();
System.out.println("Enter the Student name.");
    studentName=sc.next();
System.out.println("Enter the Blood Group of Student.");
group=sc.next();

System.out.println("Enter the Number of courses.");
noOfCourses=sc.nextLong();
courses=new LinkedHashSet<Courses>();
Courses courses2=null;

for(long l=0;l<noOfCourses;l++){
courses2=new Courses();
System.out.println("Enter the Student Course Id.");
studentCourseId=sc.nextLong();
System.out.println("Enter the Student Course Name");
courseName=sc.next();

courses2.setCourseId(studentCourseId);
courses2.setCourseName(courseName);
courses.add(courses2);
}

public void updateStudentDetailsOtmDao(long studentId,String studentName, String group, Set<Courses> courses) throws Exception{
    Session session=null;
    try{
        if(factory!=null && !factory.isClosed()){
            session=factory.openSession();
            session.beginTransaction();

            Student student=(Student)session.get(Student.class, studentId);
            student.setStudentName(studentName);
            student.setGrp(group);
            student.setCourses(courses);
            session.update(student);

            session.getTransaction().commit();
            System.out.println("Successfully updated the Student");
        }else{
            System.out.println("Please check the Session Factory");
        }

    }catch(HibernateException exception){
        session.getTransaction().rollback();
        throw exception;
    }finally{
        if(session!=null){
            session.close();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

好的,如果您有Student个数据库中的课程,并希望删除现有课程并将其替换为新课程:

Student student = (Student)session.get(Student.class, studentId);

if(student.getCourses() == null) {
  student.setCourses(new ArrayList<Courses>());
}

studen.getCourses().clear();
studen.getCourses().addAll(courses);

session.merge(student);

另外,请将orphanRemoval = true添加到@OneToMany

为什么merge()

您也可以使用update()。但是对于merge(),如果您有一个Course指定的现有enrollNo,则Course将会更新。