I'm having trouble with flush() and clear() in a loop inside a transaction not persisting modified objects to database.
Sometimes it does other times it doesn't.
Here is my Entity.
import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; @Entity @Table(name = "TestEntity", schema = "mySchema") public class TestEntity { @Id private int id; @Basic @Lob private String remark; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
Here is my Test program that fails.
import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class Test { private final EntityManagerFactory emf; private final EntityManager em; public Test() { emf = Persistence.createEntityManagerFactory("$objectdb/db/test.odb"); em = emf.createEntityManager(); } public static void main(String[] args) { Test t = new Test(); t.doit(); } public void doit() { String sbs = "This is a test String"; em.getTransaction().begin(); for(int i=0;i<Integer.MAX_VALUE;i++) { TestEntity v = new TestEntity(); v.setId(i); em.persist(v); v.setRemark(sbs); if(i % 10 == 0) { System.out.println("flushing"); em.flush(); em.clear(); } System.out.println("i="+i); TestEntity t1 = em.find(TestEntity.class, i); String rem = t1==null ? null : t1.getRemark(); if(rem==null || rem.compareTo(sbs)!=0) { System.out.println("Validate failed for i="+i); System.out.println("t1="+t1); System.out.println("rem="+rem); System.exit(1); } } em.getTransaction().commit(); } }
Here is my failure output.
i=75
i=76
i=77
i=78
i=79
flushing
i=80
Validate failed for i=80
t1=null
rem=null