【发布时间】:2016-03-22 14:42:30
【问题描述】:
我需要创建一个带有hibernate但没有spring框架的rest web服务项目。
我已经创建了一个 maven 项目、模型、Dao 和服务包
请你帮我或告诉我一个教程??
【问题讨论】:
我需要创建一个带有hibernate但没有spring框架的rest web服务项目。
我已经创建了一个 maven 项目、模型、Dao 和服务包
请你帮我或告诉我一个教程??
【问题讨论】:
使用 HK2 of jersey,你不需要使用 web xml 文件:
1) 创建一个应用类:
@ApplicationPath("rest")
public class Application extends ResourceConfig {
public SapApplication() {
packages("sap.ressources", "sap.providers");
registerInstances(new SapBinder());
register(MoxyJsonFeature.class);
}
}
接下来您将创建一个这样的 Bind 类:
public class Binder extends AbstractBinder {
@Override
protected void configure() {
bind(ADAOImpl.class).to(ADAO.class);
} // implement class to inteface use the same thing for services classes
您还需要创建一个侦听器才能在 DAO 类中创建一个 entityManager:
@WebListener
public class LocalEntityManagerFactory implements ServletContextListener {
private static EntityManagerFactory emf;
@Override
public void contextInitialized(ServletContextEvent event) {
emf = Persistence.createEntityManagerFactory("myPU");// myPu : is a name of persistence-unit in persistence xml file
}
@Override
public void contextDestroyed(ServletContextEvent event) {
if (emf != null) {
emf.close();
}
}
public static EntityManager createEntityManager() {
if (emf == null) {
throw new IllegalStateException("Context is not initialized yet.");
}
return emf.createEntityManager();
}
就是这样,现在你可以创建你的休息服务了。
【讨论】: