Spring/spring_유용한것

jpa one to many 관련

slow333 2023. 6. 7. 15:26

애러 발생

detached entity passed to persist: sb.lec total.hibernate Entities.oneToMany

 

many to one 측면에서 데이터가 생성되지 않은 상태에서 one to many에 저장하거나

데이터 가 생성되기 전에 foreign key를 설정하려 하면 발생(어찌 보면 당연한...)

many to one에 모든 데이터가 저장되고 난 후에 one to many에 리스트를 저장해야 함

결국 순서가 중요

* one to many가 기본으로 lazy가 설정되어 있어 @Transactional 을 해야 수행됨

(이를 피할려면 eager로 해야함)

* 참고로 test에서 수행시 @Transactional을 하면 수행 후 데이터는 지워짐...

관련 코드...

@Entity
public class Instructor {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String firstName;
private String lastName;
private String email;

@JoinColumn(name = "instructor_detail_id")
@OneToOne(cascade = CascadeType.ALL)
private InstructorDetail instructorDetail;

@OneToMany(mappedBy = "instructor",
cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, fetch = FetchType.EAGER)
private List<Course> courses;

public void addCourse(Course theCourse) {
if (courses == null) {
courses = new ArrayList<>();
}
courses.add(theCourse);
theCourse.setInstructor(this);
}   ............ 생략
@Entity
public class Course {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String title;

@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, fetch = FetchType.EAGER)
@JoinColumn(name = "instructor_id")
private Instructor instructor;      ...... 생략
@Test
// @Transactional
public void OneToManyCourse(){
Instructor tempInstructor = instructorRepo.findById(7L).get();
Course course1 = new Course("new 2 ----- ");
Course course2 = new Course("new 2 ====== 보기");

courseRepo.save(course1);
courseRepo.save(course2);

course1.setInstructor(tempInstructor);
course2.setInstructor(tempInstructor);

courseRepo.save(course1);
courseRepo.save(course2);

tempInstructor.addCourse(course1);
tempInstructor.addCourse(course2);
}

*** delete 수행 시해는 foreign key를 null로 설정하고 저장한 후에 지워야 함... 아니면 안 지워짐

    @Test
    public void deleteCourse(){
        Course course = courseRepo.findById(13L).get();
        course.setInstructor(null);
        courseRepo.save(course);
        courseRepo.delete(course);
    }

'Spring > spring_유용한것' 카테고리의 다른 글

Rest api java filter  (0) 2023.06.09
java logger, sleep  (0) 2023.06.08
jpa tip  (0) 2023.06.06
data base-mysql  (0) 2023.06.06
html input type  (0) 2023.06.05