How and to whom should I introduce PersistenceContext when running tests through Jersey / Grizzly?

I have this class (combination of JAX-RS / Jersey and JPA / Hibernate):

public class Factory {
  @PersistenceContext(unitName = "abc")
  EntityManager em;
  @Path("/{id}")
  @GET
  public String read(@PathParam("id") int i) {
    return em.find(Employee.class, i).getName();
  }
}

This is unit test:

public class FactoryTest extends JerseyTest {
  public FactoryTest() throws Exception {
    super("com.XXX");
  }
  @Test
  public void testReadingWorks() {
    String name = resource().path("/1").get(String.class);
    assert(name.length() > 0);
  }
}

Everything is fine here, except for one thing: it emis NULLinside read(). It seems that the grizzly bear (I use this server along with the Jersey test platform) does not introduce PersistenceContext. What am I doing wrong here?

+3
source share
2 answers

Everything is fine here, except for one: em - NULL inside read (). It seems that Grizzly (I use this server along with the Jersey test platform) does not embed PersistenceContext. What am I doing wrong here?

  • , .
  • , "" (Paul Sandoz, , , , ).

, EntityManager EJB 3.1 Bean (SLSB), REST ( JAX-RS ).

JAX-RS Bean CDI . , TOTD # 124: CDI + JPA JAX-RS JAX-WS.

, , Embedded GlassFish .

+2

com.sun.jersey/jersey-grizzly2 1.x. InjectableProvider. Oracle:

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.ext.Provider;

import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;

@Provider
public class EJBProvider implements InjectableProvider<EJB, Type> {

    public Scope getScope() {
        return Scope.Singleton;
    }

    public Injectable getInjectable(ComponentContext cc, EJB ejb, Type t) {
        if (!(t instanceof Class)) return null;

        try {
            Class c = (Class)t;        
            Context ic = new InitialContext();

            final Object o = ic.lookup(c.getName());

            return new Injectable<Object>() {
                public Object getValue(HttpContext c) {
                    return o;
                }                    
            };            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

. , , , ( ).

+1

Source: https://habr.com/ru/post/1766999/


All Articles