What is the difference between @Inject and @PersistenceContext?

南笙酒味 提交于 2019-12-08 16:22:40

问题


In a project using JPA, I commonly use

@Inject EntityManager em;

in order to obtain such an object. I saw that many code snippets in the web instead use:

@PersistenceContext EntityManager em;

What is the difference between these options?

My code runs on JBoss EAP 6.1 and Hibernate.


回答1:


@PersistenceContext is a specific annotation that declares a dependency on a container-managed entity manager. It allows you to specify more parameters like the persistence type. Setting the persistence type to EXTENDED is important when you want to maintain the persistence context for the whole life cycle of a stateful session bean. @PersistenceContext is a JPA annotation.

@Inject is a CDI annotation. It is very generic and can be used to inject a wide variety of objects.




回答2:


@PersistenceContext is a very specific annotation and it's saying "inject this field with a persistence context". You can't use it outside of a managed context.

@Inject on the other hand, is very generic. It says, "you should inject this field." It's not necessarily for a persistence context, but anything you want to define as injected.

This article (which is not exactly apples to apples of what you're asking) may shed more light on it for you.

If you want to go straight to the source of what @Inject is, you can read the spec here:

@Inject, identifies a point at which a dependency on a Java class or interface can be injected. The container then provides the needed resource. In this example, the Login bean specifies two injection points.




回答3:


@Inject will provide you with what the container deems to be the EntityManager hopefully there is only one.

However, if you happen to have more than one you'd have to go through some qualifier annotations and have something producing it for you or you can pass in the unitName attribute to the @PersistenceContext annotation.



来源:https://stackoverflow.com/questions/16598318/what-is-the-difference-between-inject-and-persistencecontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!