different find and getReference in entityManager

11 views Asked by At

when I run those codes below , I see an error: Caused by: Removing a detached instance ...

// in SinhVienDAOIlpm.java
@Override
    public SinhVien getById(int id) {
        return this.entityManager.find(SinhVien.class, id);
    }
@Override
    public void deleteStudent(SinhVien sv) {
        this.entityManager.remove(sv);
    }

// in main.java
private void deleteByID(SinhVienDAOImpl sinhVienDAOImpl) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter Student's Id: ");
    int id = scanner.nextInt();
    scanner.nextLine();
    SinhVien sinhVien = sinhVienDAOImpl.getById(id);
    if (sinhVien==null) System.out.println("Can't find !!!");
    else {
        sinhVienDAOImpl.deleteStudent(sinhVien);
        System.out.println("Deleted!!!");
    }
}

when I change entityManager.find to entityManager.getReference , it work good but i want to know clearly about the problem when I use entityManager.find

I hope to see the best explain ^^

0

There are 0 answers