I have a problem with JPA EntityManagerFactory probably. My code
import entity.ProgrammEQ;
import entity.Student;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
/**
*
* @author Kristián
*/
public class Zapoctovka_priklad {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("zapoctovka_prikladPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Student stud1 = new Student("Tom", "Pri");
Student stud2 = new Student("Jan", "Pol");
Student stud3 = new Student("Kris", "Str");
em.persist(stud1);
em.persist(stud2);
em.persist(stud3);
em.getTransaction().commit();
em.close();
emf.close();
zaradNeprihlasenych("Aplikovaná informatika");
}
public static void zaradNeprihlasenych(String programmName) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("zapoctovka_prikladPU");
EntityManager em = emf.createEntityManager();
Query q1 = em.createQuery("SELECT a FROM Student a WHERE a.StudProgram = NULL");
System.out.println("ahoj" + q1.getResultList().toString());
em.getTransaction().begin();
ProgrammEQ prog = new ProgrammEQ();
prog.setIdEQ(programmName);
prog.setStudentCount(0);
List<Student> studenti = q1.getResultList();
for (Student s : studenti) {
System.out.println(s);
s.setStudProgram(prog);
}
em.persist(prog);
em.getTransaction().commit();
em.close();
emf.close();
}
}
I have a problem. Becouse when I insert data into table student, it is okay. After that, when I close EntityManager and EntityManagerFactory, and in another function I want to add some properties, my table is empty. I tried a lot of things, but I dont know how to do that. When I called my query in main function, it returns right results. But when I call this query in function zoradNeprihlasenych, it returns null. When I remove emf.close()
anotation, it works well. How to do that? I need to do that in another function outside the function.
Try to set Table Generation Strategy
to create
and Validation strategy
to none
in persistence.xml
.