【问题标题】:how create a rest web service project with hibernate tomcat 7 postgres without spring如何在没有spring的情况下使用hibernate tomcat 7 postgres创建一个rest web服务项目
【发布时间】:2016-03-22 14:42:30
【问题描述】:

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

我已经创建了一个 maven 项目、模型、Dao 和服务包

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

【问题讨论】:

  • 也许这个带有 EJB 的 tutorial 可能有用,使用 Mysql 而不是 Postgress 但更改数据库很容易,example

标签: hibernate rest


【解决方案1】:

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

就是这样,现在你可以创建你的休息服务了。

【讨论】:

    猜你喜欢
    • 2015-06-07
    • 2011-03-10
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2013-09-20
    • 2015-12-26
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多