Injecting hibernate session to Jersey using HK2 - java

I'm developing little app and have some issues with DI.
I have a repository class for persisting my entities which I inject to my service. And I'd like to inject Session object to it using H2K.
For this purpose I try do something similar described in following SO posts:
Jersey + HK2 + Grizzly: Proper way to inject EntityManager?
Using Jersey 2.0, how do you register a bindable instance per request?
How do I properly configure an EntityManager in a jersey / hk2 application?
So I created SFFactory class and register it in ApplicationConfig.
SFFactory.java
import org.glassfish.hk2.api.Factory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class SFFactory implements Factory<Session> {
private SessionFactory factory;
public SFFactory() {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder srBuilder = new StandardServiceRegistryBuilder();
srBuilder.applySettings(configuration.getProperties());
factory = configuration.buildSessionFactory(srBuilder.build());
}
#Override
public Session provide() {
return factory.openSession();
}
#Override
public void dispose(Session session) {
if (session.isOpen()) {
session.close();
}
}
}
ApplicationConfig.java
import org.alexdzot.phonettesttask.repository.MessageRepository;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.hibernate.Session;
import javax.inject.Singleton;
import javax.ws.rs.ApplicationPath;
#ApplicationPath("/rest/*")
public class ApplicationConfig extends ResourceConfig {
public ApplicationConfig() {
packages("org.alexdzot.phonettesttask");
register(new AbstractBinder() {
#Override
protected void configure() {
bindFactory(SFFactory.class).to(Session.class);
bindFactory(MessageRepositoryFactory.class).to(MessageRepository.class).in(Singleton.class);
}
});
}
}
DefaultMessageRepository
import org.alexdzot.phonettesttask.model.Message;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.jvnet.hk2.annotations.Service;
import javax.inject.Inject;
import java.util.List;
#Service
public class DefaultMessageRepository implements MessageRepository {
#Inject
private Session session;
public void saveMessage(Message message) {
Session session = null;
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(message);
tx.commit();
} catch (Exception e) {
tx.rollback();
} finally {
session.close();
}
}
public List<Message> getAllMessages() {
Session session = null;
Transaction tx = null;
List<Message> messages = null;
try {
tx = session.beginTransaction();
messages = session.createCriteria(Message.class).list();
} catch (Exception e) {
tx.rollback();
} finally {
session.close();
return messages;
}
}
}
But when I run the app and trying to call repository methods I get NullPoinerException. I can't understand what am I doing wrong.
This is what Tomcat log is saying:
*08-Aug-2015 02:42:18.232 SEVERE [http-nio-8080-exec-10] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [org.alexdzot.phonettesttask.config.ApplicationConfig] in context with path [] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.alexdzot.phonettesttask.repository.DefaultMessageRepository.getAllMessages(DefaultMessageRepository.java:42)
at org.alexdzot.phonettesttask.service.MessageResource.viewSentMessages(MessageResource.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:308)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:291)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1140)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:403)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)*
Any ideas what wrong with my solution and what causes that problem?

Main problem:
[java.lang.NullPointerException]
Look at your repository class
#Service
public class DefaultMessageRepository implements MessageRepository {
#Inject
private Session session; <-------------------+
| // You shadow session
public void saveMessage(Message message) { |
Session session = null; <--------------+
Transaction tx = null;
try {
tx = session.beginTransaction();
...
}
...
}
You are shadowing the injected field session. So you are just using the local session, which is null. So in your method, just get rid of Session session = null;. The injection should work fine, and you should be able to just use the session field.
Another Problem:
The same Session is being used for all request. Since DefaultMessagFactory is a singleton, HK2 asserts that Session should also be a singleton, since it is contained within a singleton. So instead of making the SFFactory the default #PerLookup scope, you get a factory that is a singleton, and so only one Session will be created. This is not the behavior you should want. You can test this by putting some print statements inside your factory class.
One way to make sure that a new Session is created for each request is to:
Use javax.inject.Provider<Session>, to lazily load the session, which will allow use to keep it in the scope we configured.
#Inject
private javax.inject.Provider<Session> session;
#Override
public void saveEvent(Event event) {
Session s = session.get();
Transaction tx = s.beginTransaction();
Configure the SFFactory in a request scope
#Override
protected void configure() {
bindFactory(SFFactory.class)
.to(Session.class)
.in(RequestScoped.class);
}
The other thing to fix is that SessionFactory should be a single instance through the application. For that we can create a single factory for it, and inject it into the SFFactory. For example
public class SessionFactoryFactory implements Factory<SessionFactory> {
private final SessionFactory factory;
public SessionFactoryFactory() {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder srBuilder = new StandardServiceRegistryBuilder();
srBuilder.applySettings(configuration.getProperties());
factory = configuration.buildSessionFactory(srBuilder.build());
System.out.println("--- SessionFactory Created ---");
}
#Override
public SessionFactory provide() {
System.out.println("--- SessionFactory Provided ---");
return factory;
}
#Override
public void dispose(SessionFactory factory) {
factory.close();
}
}
The in your SFFactory
public class SFFactory implements Factory<Session> {
private final SessionFactory factory;
#Inject
public SFFactory(SessionFactory factory) {
this.factory = factory;
}
#Override
public Session provide() {
System.out.println("--- Session Created ---");
return factory.openSession();
}
#Override
public void dispose(Session session) {
if (session.isOpen()) {
session.close();
}
}
}
You configuration would change to look like
#Override
protected void configure() {
bindFactory(SessionFactoryFactory.class)
.to(SessionFactory.class)
.in(Singleton.class);
bindFactory(SFFactory.class)
.to(Session.class)
.in(RequestScoped.class);
}
UPDATE
So it seems aside from the shadowing, another main problem was in the MessageRepositoryFactory that the OP didn't show (in github project from comments).
public class MessageRepositoryFactory implements Factory<MessageRepository> {
#Override
public MessageRepository provider() {
return new DefaultMessageRepository();
}
...
}
When you instantiate the object your self, by default, the framework doesn't handle the injection. So that's why the injection of the Session didn't happen.
Instead of using the a Factory like this, you could simply bind like this
bind(DefaultMessageRepository.class).to(MessageRepository.class).in(..);
This way the framework creates the instance. The Factory should really only be used where it is not possible to bind the above way, for instance you have some initializations to do. We could have even not created the Factory for the SessionFactoryFactory and instead did all the session factory configuration elsewhere and just binded the instance. For example
SessionFactory sessionFactory =...
...
bind(sessionFactory).to(SessionFactory.class);
We just bind a SessionFactory singleton.

Related

Configure Spring transactions or EJB CMT instead

I tried to configure Spring Boot with Hibernate:
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import org.datalis.plugin.database.dao.TerminalsService;
import org.datalis.plugin.database.models.TerminalsModel;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Qualifier("terminalsService")
public class TerminalsDaoHibernate implements TerminalsService {
#Autowired
private EntityManager entityManager;
#Override
#Transactional
public TerminalsModel getTerminalToken(String terminalToken) throws Exception {
TerminalsModel terminal = null;
Session session = entityManager.unwrap(Session.class);
try {
entityManager.getTransaction().begin();
terminal = (TerminalsModel) session.get(TerminalsModel.class, terminalToken);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
throw new Exception("Error");
}
return terminal;
}
}
But I get this error:
14:47:34,323 ERROR [stderr] (default task-1) java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
14:47:34,323 ERROR [stderr] (default task-1) at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:255)
What is the proper way to configure #Transactional properly?
Do I need to use Transaction is a different way?
You are using #Transactional and still are trying to manually start a transaction. Either do manual transaction management (i.e remove the #Transactional) or embrace #Transactional by removing the manual transaction management code.
#Override
#Transactional
public TerminalsModel getTerminalToken(String terminalToken) throws Exception {
TerminalsModel terminal = null;
Session session = entityManager.unwrap(Session.class);
return (TerminalsModel) session.get(TerminalsModel.class, terminalToken);
}
However I don't see why you would want to use plain Hibernate over JPA here. The same result can be achieved by using JPA.
#Override
#Transactional
public TerminalsModel getTerminalToken(String terminalToken) throws Exception {
return entityManager.find(TerminalsModel.class, terminalToken);
}
Generally there is no need to use the plain Hibernate API over JPA with the current state of the JPA API.

EntityManager em.getTransaction().begin() locks thread

My question is, if the method "begin()" is capable of lock a thread further than the "timeout" config in the persistence.xml.
Here is a snippet:
#Inject EntityManager em;
#Inject ContextControl ctxCtrl;
String fileType;
String fileName;
String hash;
BufferedReader reader = null;
public void run(File f, String fileType, String hash) throws ProcessorException, IOException{
this.fileType = fileType;
this.hash= hash;
this.fileName = f.getName();
try {
ctxCtrl.startContext(RequestScoped.class);
em.getTransaction().begin();
reader = openReader(f);
//rest of the code...
em.getTransaction().commit();
}catch (Exception e) {
logger.error(e.getMessage(), e);
try{ //for database breakdown purpose
em.getTransaction().rollback();
}catch(Exception e2){
logger.error(e2.getMessage(), e2);
throw new ProcessorException();
}
throw new ProcessorException();
}finally{
reader.close();
ctxCtrl.stopContext(RequestScoped.class);
}
"run" method is executed inside a loop. This method is executed serially, there is no possible concurrency.
Now, the thing is that the thread stops randomly at line "em.getTransaction().begin();", with no exception. And since this is a critical area, all the application is stopped and the lock is never released.
The only thing I can think of is the "begin()" method getting stuck somehow, but not in an exception way, but rather in a lock way (since no exception is caught).
I wasn't able to recreate the issue, I can only say that the issue has nothing to do with the file. Also, this is happening in production, so I can't debug the application other than check some logs
thanks in advance
EDIT
I use Deltaspike to provide the CDI. Entitymanager it's injected anytime it's needed. It's created like this:
CLASS ENTITYMANAGER FACTORY PRODUCER
import java.io.FileInputStream;
import java.util.Properties;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.slf4j.Logger;
#ApplicationScoped
public class EntityManagerFactoryProducer {
#Inject Logger logger;
#Produces
#ApplicationScoped
public EntityManagerFactory create() {
Properties props = new Properties();
try {
props.load(new FileInputStream("cfg/connection.properties"));
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return Persistence.createEntityManagerFactory("scgach",props);
}
public void destroy(#Disposes EntityManagerFactory factory) {
factory.close();
}
}
CLASS ENTITYMANAGER PRODUCER
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
#ApplicationScoped
public class EntityManagerProducer {
#Inject EntityManagerFactory emf;
#Produces #RequestScoped
public EntityManager create() {
return emf.createEntityManager();
}
public void destroy(#Disposes EntityManager em) {
if(em.isOpen())
em.close();
}
}

NameAlreadyBoundException using JNDI

I created a session bean with this code:
package ejb2;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
#Stateless(name = "TestEJB", mappedName = "EJB2-Project1-TestEJB")
public class TestEJBBean implements TestEJB, TestEJBLocal {
#Resource
SessionContext sessionContext;
public TestEJBBean() {
}
public String getHello(String who_welcome) {
return "Hello " + who_welcome;
}
}
As you can see, it's almost a default code (except getHello method). Besides this bean I have a client:
package ejb2;
import java.util.Hashtable;
import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class TestEJBClient {
public static void main(String[] args) {
try {
final Context context = getInitialContext();
TestEJB testEJB = (TestEJB) context.lookup("EJB2-Project1-TestEJB#ejb2.TestEJB");
System.out.println(testEJB.getHello("Student"));
} catch (CommunicationException ex) {
System.out.println(ex.getClass().getName());
System.out.println(ex.getRootCause().getLocalizedMessage());
System.out.println("\n*** A CommunicationException was raised. This typically\n*** occurs when the target WebLogic server is not running.\n");
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static Context getInitialContext() throws NamingException {
Hashtable env = new Hashtable();
// WebLogic Server 10.x/12.x connection details
env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, "t3://localhost:7101");
return new InitialContext(env);
}
}
First time it worked like a charm. But then I created another bean:
package ejb2;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.naming.InitialContext;
#Stateless(name = "ClientEJB", mappedName = "EJB2-Project1-ClientEJB")
public class ClientEJBBean implements ClientEJB, ClientEJBLocal {
#Resource
SessionContext sessionContext;
TestEJB testEJB;
public ClientEJBBean() {
try {
final Context context = new InitialContext();
testEJB = (TestEJB) context.lookup("EJB2-Project1-TestEJB#ejb2.TestEJB");
} catch (Exception ex) {
ex.printStackTrace();
}
}
public String getHelloFromBean(String who) {
return testEJB.getHello(who);
}
}
And now beans aren't working. I get an error like this:
weblogic.application.ModuleException: Unable to bind Business Interface to the JNDI name: EJB2Project1WebApp_warClientEJB_Home, throw exception javax.naming.NameAlreadyBoundException: [EJB:011224]Unable to bind the interface ejb2.ClientEJB to ClientEJB. Another EJB has already bound an interface to that name.; remaining name 'EJB2-Project1-ClientEJB#ejb2'. NestedException Message is :[EJB:011224]Unable to bind the interface ejb2.ClientEJB to ClientEJB. Another EJB has already bound an interface to that name.
What's the problem with these codes?
As far as i can see you try to deploy two stateless EJBs with the same JNDI name
Try to undeploy the current application , check the JNDI tree from Admin Console
and make sure the tree does not have the JNDI name you see as duplicate.

How to run Application Client on the GlassFish Server 4 from command line

I just started to learn EJB and I wrote a simple bean and client application. Below is a code:
Interface:
package ejb;
import javax.ejb.Remote;
#Remote
public interface MySessionRemote {
String getResult();
}
Bean:
import javax.ejb.EJB;
import javax.ejb.Stateless;
#Stateless
public class MySession implements MySessionRemote {
// #EJB
//private static MySessionRemote mySession1;
#Override
public String getResult() {
return "Bean";
}
}
Client application:
package entappclient;
import javax.naming.*;
import ejb.MySessionRemote;
import java.util.Properties;
import javax.ejb.EJB;
public class Main {
// #EJB private static MySessionRemote mySession;
public static void main(String[] args) {
// TODO code application logic here
new Main().Save();
}
public Context getContext() throws javax.naming.NamingException {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial",
"com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs",
"com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state",
"com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
return new InitialContext(props);
}
public void Save () {
//System.out.println(mySession1.getResult());
try {
Context jndiContext = getContext();
System.out.println("0");
MySessionRemote ref = ySessionRemote)jndiContext.lookup("java:global/EntAppEJB- ejb/MySession!ejb.MySessionRemote");
System.out.println("1");
System.out.println(ref.getResult());
} catch (Exception e ) {
System.out.println("Save"+e);
}
}
}
When I run it under NetBeans 8 everything works fine. The result is:
0
1
Bean
But when I try to run this from command line using : appclient - client path/EntAppClient.jar, it does not work. The result is:
0
Savejavax.naming.NamingException: Lookup failed for 'java:global/EntAppEJB-ejb/M
ySession!ejb.MySessionRemote' in SerialContext[myEnv={java.naming.factory.initia
l=com.sun.enterprise.naming.SerialInitContextFactory, org.omg.CORBA.ORBInitialHo
st=localhost, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.J
NDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Ro
ot exception is javax.naming.NamingException: ejb ref resolution error for remot
e business interfaceejb.MySessionRemote [Root exception is java.lang.ClassNotFou
ndException: ejb.MySessionRemote]]
Can anybody help me to find out why I can run this under NetBeans but it does not work from command line.
Best regards
Marcin

Stateless is not working in AS 7

I'm getting this:
[org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/PontoComentario].[jsp]] (http--0.0.0.0-8080-2) Servlet.service() for servlet jsp threw exception: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:149) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:195) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185) [hibernate-core-4.0.1.Final.jar:4.0.1.Final
After acessing the jsp. My EMFactory is like this:
import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.transaction.UserTransaction;
#Stateless
public class EMFactory {
public static EntityManager getEntityManager() {
try {
Context ctx = new InitialContext();
return (EntityManager) ctx.lookup("java:comp/env/PontoComentario/EntityManager");
} catch (Exception e) {
return null;
}
}
public static UserTransaction getUserTransaction() {
try {
Context ctx = new InitialContext();
return (UserTransaction) ctx.lookup("java:comp/UserTransaction");
} catch (Exception e) {
return null;
}
}
}
I'm not sure why i'm getting that, i was using AS 5 and it was working nice. If you need any other piece of code just ask.
This is a sad part of scriptlets that was use in the jsp:
<%
UsuarioDao dao = new UsuarioDao();
List<Usuario> lista;
if (usuarioLogado.getAdministrador()) {
lista = dao.getListOrder("codigo");
} else {
lista = dao.getListCond("obj.administrador = true order by obj.codigo");
... and so on.
Why don't you simply inject a reference to the EntityManager with an annotation:
#PersistenceContext
EntityManager em;
And are you really accessing your SLSB from a JSP? Not from a servlet controller?

Categories

Resources