based on this example :
@Service
public class Purchase {
@PersistenceContext
private EntityManager em;
@Autowired
private PurchaseDAO dao;
private String normalField;
.... // methods, operations, etc
}
Please help correct me if im mistaken :
Thank you !
Answer: No. Spring don't give you thread safety for their bean. Spring provide different type of bean scope like (Prototype,Singleton etc). If Prototype then a new bean create each time it invoke where a singleton bean created for one time and shared in application context .
In a standard servlet-based Spring web application, every new HTTP request generates a new thread. If the container creates a new bean instance just for that particular request, we can say this bean is thread-safe.
You can use the @PersistenceContext annotation to inject an EntityManager in an EJB 3.0 client (such as a stateful or stateless session bean, message-driven bean, or servlet). You can use @PersistenceContext attribute unitName to specify a persistence unit by name, as Example 29-13 shows.
You don't need to make those methods synchronized, they are thread safe as it is. Yeah, it probably makes sense to make DbService a singleton. Alternatively, you could just make em static.
SpringSource forums: I have been looking for answers to the same question on the forum... The general concensus seems to be that while EntityManager is not thread safe per JPA specs, the EntityManager injected by Spring through its EntityManager proxy may be.
Hibernate: 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. An EntityManager will not obtain a JDBC Connection (or a Datasource) unless it is needed, so you may safely open and close an EntityManager even if you are not sure that data access will be needed to serve a particular request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With