好的,所以我想在一个表中映射组和学生,但我有一个错误:“对象引用未保存的瞬态实例”。如果我向所有人添加级联,它会说这个对象arleady存在。有什么问题?
以下是实体:
@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);
答案 0 :(得分:0)
dodajListeOsob
抛出object references an unsaved transient instance
listaOsob
包含grupa
(@ManyToOne
),这在数据库中不存在grupa
在数据库中不存在,因为dodajGrupe
不像其他方法那样persist
dodajListeOsob
也不会调用persist
(在这种情况下不会导致任何问题)