gpt4 book ai didi

java - Hibernate、多线程和 CascadeType.ALL

转载 作者:太空宇宙 更新时间:2023-11-04 07:29:23 24 4
gpt4 key购买 nike

在多线程环境中,

这有效

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();
}

但这不是

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();
}

我收到如下错误:“对象引用未保存的 transient 实例”、“具有相同标识符值的不同对象已与 session 关联”

有什么想法吗?

这是一个重现该问题的最小 Maven 项目:http://www.2shared.com/file/bGLmJ6aO/example.html

详细信息

java 版本“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 is an expensive-to-create, threadsafe object intended to be shared by all application threads. It is created once, usually on application startup.

An EntityManager is an inexpensive, non-threadsafe object that should be used once, for a single business process, a single unit of work, and then discarded. ...

参见:http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html_single/#transactions-basics

我不太确定你在做什么,但如果你从多个线程使用相同的静态EntityManager,那么这就是你的问题。

EntityManagerFactory是您想要共享的线程安全对象,但您应该为每个正在执行的请求/工作单元创建一个新的EntityManager。

关于java - Hibernate、多线程和 CascadeType.ALL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17983275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com