我想知道我需要做什么才能访问数据库线程安全。
这是我的Entity类:
@Entity @Table(name = "students") @NamedQuery(name = "Student.getAll", query = "SELECT s FROM Student s") public class Student { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(length = 32, name = "name") private String name; // ... constructor, getters and setters, toString ... }
这是DbService类:
public class DbService { public EntityManager em = Persistence .createEntityManagerFactory("MyPersistenceUnit") .createEntityManager(); public Student add(Student student) { EntityTransaction tx = em.getTransaction(); tx.begin(); Student studentFromDb = em.merge(student); tx.commit(); return studentFromDb; } public void delete(long id) { EntityTransaction tx = em.getTransaction(); tx.begin(); em.remove(get(id)); tx.commit(); } public Student get(long id) { return em.find(Student.class, id); } public void update(Student student) { EntityTransaction tx = em.getTransaction(); tx.begin(); em.merge(student); tx.commit(); } public List<Student> getAll() { TypedQuery<Student> namedQuery = em.createNamedQuery("Student.getAll", Student.class); return namedQuery.getResultList(); } }
这是与DbService一起使用的类:
public class SomeDbWorker implements Runnable { @Override public void run() { DbService service = new DbService(); // do something ... service.add( ... ); service.delete( ... ); service.getAll(); // ... } }
不需要同步任何东西
实体管理器不是threadSafe,而是设计为针对每个工作单元实例化并在之后销毁。
相反,工厂的创建成本很高,应该重新使用