mysql - 子表在一对多更新过程中未更新

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

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

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 来更新子表行。应该按类(class) 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();
        }
    }
}

最佳答案

好的,如果数据库中有 Student 类(class),并且想要删除现有类(class)并将其替换为新类(class):

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 将是已更新。

关于mysql - 子表在一对多更新过程中未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42719773/

相关文章:

mysql - 在 laravel 5.4 中更新查询

MYSQL WHERE NOT查询

hibernate - org.hibernate.StaleObjectStateException:行已由另一个事务更新或删除(或未保存的值映射不正确)

javascript - jQuery 通过 ID 获取子值

wordpress - 使用子主题覆盖函数functions.php

sorting - Kotlin-按对象ID和parentId对对象进行排序

mysql - 应用程序中的 Azure MySQL : "MySQL In App export operation is in progress..."

mysql - 区分mysql中大小写不同的两个字符串

java - hibernate 在选择期间锁定表多长时间?

java - Hibernate - 如何急切地加载惰性字段?