I’m trying to test a stateless session bean with an EntityManager dependency.
This is the persistence unit I create the EntityManager with:
<persistence-unit name="ThunderstormTest-PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.robinfinch.thunderstorm.customer.Customer</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:haildb"/>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbc.JDBCDriver"/>
<property name="javax.persistence.jdbc.username" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="eclipselink.target-database" value="HSQL"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>
This is the NamedQuery:
@NamedQuery(
name="findCustomerWithName",
query="select c from Customer c where c.name = :custName"
)
The problem is that after persisting a Customer,
em.find(Customer.class, id)
returns the persisted customer, but
em.createNamedQuery("findCustomerWithName")
.setParameter("custName", name)
.getResultList()
doesn’t.
The log shows both queries:
--Execute query ReadObjectQuery(name="readObject" referenceClass=Customer sql="SELECT ID, NAME FROM CUSTOMER WHERE (ID = ?)")
--Execute query ReadAllQuery(name="findCustomerWithName" referenceClass=Customer sql="SELECT ID, NAME FROM CUSTOMER WHERE (NAME = ?)")
When I use a ProgreSQL database, everything works as expected.
Any idea’s to what’s going on would be much appreciated.
You need to flush the entity manager.
em.find()will use the cache to find the entity, whereas a query goes straight to the database. Obviously in this case they’re out of sync.I also noticed you’re using
RESOURCE_LOCALas the transaction type. Are you sure you want to do that? Typically when using JPA in session beans you wantJTAas the transaction type so that JPA transactions are in sync with EJB transactions. (RESOURCE_LOCALis typically for Java SE apps.) In this case, you can get around the need to flush the entity manager by turning off the cache: