Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

java - How do you create an EntityManager when you are unsure of the unit name?

I'm in a situation where I need to determine the EntityManager's unit name at run time.

For example, I'd like to do something like this:

@PersistenceContext(unitName = findAppropriateJdbcName())
EntityManager entityManager;

However, this is not possible with annotations.

Is it possible to create the EntityManager when your not sure of what the unit name is until run time?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is possible to specify the persistence unit (PU) name at runtime, but this is a parameter used in the creation of the EntityManagerFactory, not an individual EntityManager. See the Javadoc for the Persistence class method createEntityManagerFactory(). Example:

EntityManagerFactory emf = Persistence.createEntityManagerFactory(unitname);
EntityManager em = emf.createEntityManager();
// ...

I do this in a non-Java EE application (using Java 6 SE calls in a Tomcat-hosted web app) but I'm not sure how you do the same thing in a container-managed Java EE 6 application. It is possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...