0

好的,所以我想在一个表中获取映射的组和学生,但我遇到了一个错误:“对象引用了一个未保存的瞬态实例”。如果我将级联添加到所有内容中,它会说这个对象已经存在。怎么了 ?

以下是实体:

 @Entity  
 @Table(name = "listaosob") 
 public class listaOsob implements Serializable {

@Id
@GeneratedValue
private int id;
private static final long serialVersionUID = 1L;
@ManyToOne
private Student student;
@ManyToOne
private Grupa grupa;

@Entity  
@Table(name = "student") 
public class Student implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private int id;
private String imie;
private String nazwisko;
private String login;
private String haslo;
@Column(unique=true)
private int nr_albumu;
@Column(unique=true)
private String kod_karty;

 @Entity  
 @Table(name = "grupa") 
 public class Grupa implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private int id;
private String nazwa;
private Time godzina;
private String sala;
private String tydzien;
@ManyToOne
private Prowadzacy prowadzacy;

ejb代码:

 @Stateless
 @LocalBean
 public class StudentBean implements StudentBeanRemote, StudentBeanLocal {

 @PersistenceContext  
 private EntityManager eM; 

public StudentBean() {}

public void dodajStudenta(Student s) {
    eM.persist(s);
    eM.flush();
}

public void usunStudenta(Student s) {
    eM.remove(s);  
    eM.flush();
}

@SuppressWarnings("unchecked")
public ArrayList<Student> listaStudentow() {
    Query query = eM.createQuery("SELECT e FROM student e");
    return (ArrayList<Student>) query.getResultList();
}

@SuppressWarnings("unchecked")
public ArrayList<Student> listaStudentow(Grupa grupa) {
    Query query = eM.createQuery("SELECT e FROM listaosob e WHERE e.grupa = :grupa");
    query.setParameter("grupa", grupa);
    return (ArrayList<Student>) query.getResultList();
}

public void dodajGrupe(Grupa g) {
    eM.persist(g);
}

public void usunGrupe(Grupa g) {
    eM.remove(g);  
    eM.flush();
}

public void dodajListeOsob(listaOsob l) {
    eM.persist(l);
}

和一个示例测试:

Student name1 = new Student("new"+gen.nextInt(),"nazwisko","log", "haslo", "asd"+gen.nextInt(), gen.nextInt());
            obj.dodajStudenta(name1);
            Grupa n = new Grupa();
            obj.dodajGrupe(n);
            listaOsob lista = new listaOsob(name1, n);
            obj.dodajListeOsob(lista);
4

1 回答 1

0

dodajListeOsob投掷object references an unsaved transient instance

  • 因为listaOsobcontains grupa( @ManyToOne),它在数据库中不存在
  • grupa不存在于数据库中,因为dodajGrupe不像persist其他方法那样做
  • dodajListeOsob不会调用persist(在这种情况下不会引起任何问题)
于 2013-05-14T00:27:51.257 回答