java - Hibernate, Multithreading and CascadeType.ALL -
in multithreaded environment,
this works
box box = new box("b"); toy t1 = box.addnewtoy("t1"); toy t2 = box.addnewtoy("t2"); synchronized (em) { em.gettransaction().begin(); em.persist(t1); em.gettransaction().commit(); } synchronized (em) { em.gettransaction().begin(); em.persist(t2); em.gettransaction().commit(); } but doesn't
box box = new box("b"); toy t1 = box.addnewtoy("t1"); synchronized (em) { em.gettransaction().begin(); em.persist(t1); em.gettransaction().commit(); } toy t2 = box.addnewtoy("t2"); synchronized (em) { em.gettransaction().begin(); em.persist(t2); em.gettransaction().commit(); } i errors like: "object references unsaved transient instance", "a different object same identifier value associated session"
any ideas?
here minimal maven project reproduces problem: http://www.2shared.com/file/bglmj6ao/example.html
details
java version "1.7.0_17", hibernate 4.2.3.final, ubuntu 11.04 natty, sqlite
class toy { @manytomany(mappedby="toys",fetch = fetchtype.lazy, cascade = cascadetype.all) public list<box> getboxes() { return boxes; } public void setboxes(list<box> boxes) { this.boxes = boxes; } } class box { @manytomany(fetch = fetchtype.lazy, cascade = cascadetype.all) public list<toy> gettoys() { return toys; } public void settoys(list<toy> toys) { this.toys = toys; } public toy addnewtoy(string name) { toy toy = new toy(); toy.setname(name); toy.boxes.add(this); toys.add(toy); return toy; } }
a entitymanagerfactory expensive-to-create, threadsafe object intended shared application threads. created once, on application startup.
an entitymanager inexpensive, non-threadsafe object should used once, single business process, single unit of work, , discarded. ...
see: http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html_single/#transactions-basics
i'm not sure you're doing if you're using same static entitymanager multiple threads that's problem.
the entitymanagerfactory thread-safe object want share, should create new entitymanager each request/unit of work being performed.
Comments
Post a Comment