I'm bootstrapping a new Java restful api service using jersey and hibernate.
I'm struggling to put DI into the whole thing. Specifically I can't seem to inject hibernate stuff (EntityManagerFactory
or EntityManager
) and also I'd love to de-couple the rest resource (ApiResource
) from the DAO object.
Here's a simplified version of my Jersey resource:
@Path("api")
public class ApiResource {
private DBController db;
public ApiResource() {
this.db = DBController.getInstance("YOLO");
}
@GET
@Produces({"application/json", MediaType.APPLICATION_JSON})
@Path("/history/{id}")
public void getTrends(@PathParam("id") String id) {
List<Stuff> list = db.getById(id);
return list;
}
And then the relevant DBController
(which is just a DAO) code is something like:
public class DBController {
private static DBController instance = null;
private static EntityManagerFactory sessionFactory;
private static EntityManager entityManager;
public DBController(String persistenceUnitName) {
sessionFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
entityManager = sessionFactory.createEntityManager();
}
public static DBController getInstance(String persistenceUnitName) {
if (instance == null)
instance = new DBController(persistenceUnitName);
return instance;
}
public List<Stuff> getById(String id) {
entityManager.getTransaction().begin();
List<Stuff> list = entityManager.createQuery("select b from Yolo b where b.id =: ndg", Stuff.class)
.setParameter("id", id)
.getResultList();
entityManager.getTransaction().commit();
return list.stream().collect(Collectors.toList());
}
And on my main I just do:
ResourceConfig resourceConfig = new ResourceConfig(ApiResource.class);
final Channel server = NettyHttpContainerProvider.createHttp2Server(BASE_URI, resourceConfig, null);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
server.close();
}
}));
Thread.currentThread().join();
If anyone has an example project using hibernate and jersey (and maybe weld?).
Note: I'm not using Spring (and don't want to). I can use weld or guice if needed. Not so sure what hk2 is for though.