如何在没有spring的情况下使用hibernate tomcat 7 postgres创建一个rest web服务项目



我需要创建一个带有hibernate但没有spring框架的rest web服务项目。

我已经创建了一个专业的项目,模型,道和服务包

请你帮我或者告诉我一个教程好吗??

使用jersey的HK2,您不需要使用web xml文件:

1) 创建一个应用程序类:

@ApplicationPath("rest")
    public class Application extends ResourceConfig {
        public SapApplication() {
            packages("sap.ressources", "sap.providers");
            registerInstances(new SapBinder());
            register(MoxyJsonFeature.class);
        }
}

接下来你将创建一个像这样的绑定类:

    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();
        }

仅此而已,现在您可以创建休息服务了。

最新更新