Entity Manager / persistance file structure

2019-08-08 20:24发布

问题:

The title isn't clear as I couldn't think of one but, I have an EJB project and am trying to play with JPA. To create the entity manager I am injecting it in via annotations

@PersistenceContext(unitName="testConnection")  
private EntityManager em;

When I run a test query which I believe to be fine

Query userQuery = em.createQuery("SELECT u FROM TestUser u WHERE u.username = 'test' u.password = 'test'");
tu = (TestUser) userQuery.getSingleResult();

I get an exception which points toward the EJB not being able to create the entity manager.

The strange thing is that when I run

tu = (TestUser) em.find(TestUser.class, id);

it works fine

My project structure is

  EAR
    EJB
    EJB Client
    JPA
       persistance.xml

and I guess this is the main problem

SEVERE: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName testConnection

The individual projects are currently linked using dependencies.

So any thoughts?

Thanks Jon

回答1:

I have an EJB project and am trying to play with JPA. To create the entity manager I am injecting it in via annotation

The annotation part itself looks correct.

when I run a test query which i believe to be fine

I don't think it is, it is at least missing an AND in the WHERE clause. But I would write it like this actually:

Query userQuery = em.createQuery("SELECT u FROM TestUser u WHERE u.username = :name AND u.password = :password");
userQuery.setParameter("name", "test");
userQuery.setParameter("password", "test");
tu = (TestUser) userQuery.getSingleResult();

I get an exception which points toward the EJB not being able to create the entity manager. The strange thing is that when I run (...) it works fine.

That's strange indeed given the exception that you get.

My project structure is (...)

I don't know if it's a typo or not but it's persistence.xml, not persistance.xml, and it should be located in a META-INF directory of the root of the persistence unit.

So any thoughts?

Fix the query, fix the persistence.xml packaging. Also please provide its content and the full stack trace.



回答2:

I wrote an entity manager once, but at the moment, I'm unable to access the code, but have a look at this page and the ones linked at the bottom:

http://www.javabeat.net/articles/91-ejb-30-entity-manager-2.html