Looking around StackOverflow I see answers like this one which suggest that @Produces
/@Inject
is the way to go unless one specifically needs a remote Bean. Furthermore, Adam Bien says DAO is dead, so what is the "proper" EE 7 way to @Inject
an EntityManager? Currently I have this kind of code:
@Path("/userdb")
public class UserDBInterface {
@PersistenceContext
private EntityManager em;
@GET
@Produces("text/plain")
@Transactional
public String dbInteraction()
{
User user1 = new User();
user1.setLogin("ken");
user1.setSalt(JpaSecurityUtils.getSalt());
user1.setPassword(JpaSecurityUtils.hashPassword("password", user1.getSalt()));
em.persist(user1);
return "Created User DB";
}
}
However, this gives me this error:
javax.servlet.ServletException: javax.transaction.TransactionalException: Managed bean with Transactional annotation and TxType of REQUIRED encountered exception during commit javax.transaction.RollbackException: Transaction marked for rollback.
Now, what the previous-referenced answer and this one suggest a solution like:
public class Resource {
@PersistenceContext
@Produces
EntityManager em;
}
I have actually placed that in my @WebListener
implementation of ServletContextListener
. Then my usage code becomes:
@Path("/userdb")
public class UserDBInterface {
@Inject private EntityManager em;
// ...etc as above
}
However, I now get an error:
javax.servlet.ServletException: A MultiException has 1 exceptions. They are: 1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=EntityManager,parent=UserDBInterface,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,1502799812)
If I delete the @Transactional
the injection appears to work, but I get a:
javax.servlet.ServletException: javax.persistence.TransactionRequiredException
I'm sure I'm missing something simple!