我正在使用jersey和hibernate引导新的Java Restful api服务。
我正在努力将DI融入整个过程。具体来说,我似乎无法注入休眠的内容(EntityManagerFactory
或EntityManager
),而且我也很乐意将其余资源(ApiResource
)与DAO对象分离。 >
这是我的Jersey资源的简化版本:
@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;
}
然后相关的DBController
(只是DAO)代码如下:
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());
}
我主要是做的:
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();
如果有人有使用冬眠和运动衫的示例项目(也许是焊接吗?)。
注意:我不使用Spring(并且不想使用)。如果需要,我可以使用焊缝或胶条。不确定hk2是什么。