java - 如何使Spring,Hibernate,RESTful Web服务和Gradle一起工作

标签 java spring hibernate rest gradle

我正在尝试学习Spring,Hibernate,RESTful Web服务和Gradle。

我碰到了这两个教程。

Spring 4 + Hibernate 4 +使用批注的Gradle集成示例

http://www.concretepage.com/spring-4/spring-4-hibernate-4-gradle-integration-example-using-annotation

构建RESTful Web服务

https://spring.io/guides/gs/rest-service/

我在本地测试了代码,并且在两种情况下代码均按预期执行。

现在,我试图将这两个教程组合成一个(已完成的)项目,该项目将使用Spring框架,Hibernate通过RESTful Web服务和Gradle作为构建工具连接到db。

换句话说,我想完成以下工作:

我通过URL提交以下请求: localhost:8080 / country?countryname = France ,以便调用RESTful Web服务,该服务将查询我的数据库(通过Hibernate)并以JSON格式返回正确的结果。

我取得了一些进步,但是我的配置似乎不正确。我的gradle构建成功,但是当我尝试访问localhost:8080 / country时,我得到了:

无法访问此网站

本地主机拒绝连接。
ERR_CONNECTION_REFUSED

这是我的Gradle项目:

enter image description here

build.gradle

    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE")
        }
    }

    // DB
    apply plugin: 'java'
    apply plugin: 'eclipse'
    apply plugin: 'idea'
    apply plugin: 'org.springframework.boot'


    //archivesBaseName = 'SpringHibernateRESTGradle'
    // version = '1.0-SNAPSHOT' 

    jar {
        baseName = 'countries-rest-service'
        version =  '0.1.0'
    }

    repositories {
        mavenCentral()
    }

    sourceCompatibility = 1.8
    targetCompatibility = 1.8

    dependencies {
       compile 'org.springframework.boot:spring-boot-starter-data-jpa:1.1.4.RELEASE'
       compile 'org.hibernate:hibernate-core:4.3.6.Final'
       compile 'javax.servlet:javax.servlet-api:3.1.0'
       compile 'org.slf4j:slf4j-simple:1.7.7'
       compile 'org.javassist:javassist:3.15.0-GA'
       compile 'mysql:mysql-connector-java:5.1.31'
       compile 'commons-dbcp:commons-dbcp:1.4'  
       // ws
       compile("org.springframework.boot:spring-boot-starter-web")
       testCompile('org.springframework.boot:spring-boot-starter-test')
    } 

AppConfig
    package com.pckg.config;

    import javax.sql.DataSource;

    import org.apache.commons.dbcp.BasicDataSource;
    import org.hibernate.SessionFactory;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.orm.hibernate4.HibernateTemplate;
    import org.springframework.orm.hibernate4.HibernateTransactionManager;
    import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
    import org.springframework.transaction.annotation.EnableTransactionManagement;

    import com.pckg.dao.CountryDAO;
    import com.pckg.dao.ICountryDAO;
    import com.pckg.entity.Country;

    @Configuration
    @EnableTransactionManagement
    public class AppConfig {

        @Bean
        public ICountryDAO getCountryDAO() {
            return new CountryDAO();
        }

        @Bean
        public DataSource getDataSource() {

            BasicDataSource dataSource = new BasicDataSource();

            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://localhost:3306/testing_db");
            dataSource.setUsername("****");
            dataSource.setPassword("****");

            return dataSource;
        }

        @Bean
        public SessionFactory getSessionFactory() {

            SessionFactory sessionFactory = new LocalSessionFactoryBuilder(getDataSource()).addAnnotatedClasses(Country.class).buildSessionFactory();
            return sessionFactory;

        }

        @Bean
        public HibernateTemplate getHibernateTemplate() {
            return new HibernateTemplate(getSessionFactory());
        }

        @Bean
        public HibernateTransactionManager getHibernateTransManager() {
            return new HibernateTransactionManager(getSessionFactory());
        }

    }

ServiceController
    package com.pckg.controller;

    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;

    import com.pckg.entity.Country;

    @RestController
    public class ServiceController {

        @RequestMapping("/country")
        public Country getCountryByName(@RequestParam(name = "countryname", required = false) String countryName) {

            // AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
            // ctx.register(AppConfig.class);
            // ctx.refresh();
            //
            // ICountryDAO countryDAO = ctx.getBean(ICountryDAO.class);
            // Country country = countryDAO.getCountryByName(countryName);

            // just for testing purposes - still doesn't work
            Country c = new Country();
            c.setId(2);
            c.setCountry("France");
            c.setCapital("Paris");
            c.setContinent("Europe");
            return c;

        }

    }

国家/地区DAO
    package com.pckg.dao;

    import java.util.List;

    import javax.transaction.Transactional;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.orm.hibernate4.HibernateTemplate;

    import com.pckg.entity.Country;

    @Transactional
    public class CountryDAO implements ICountryDAO {

        @Autowired
        private HibernateTemplate hibernateTemplate;

        @Override
        public List<Country> getAllCountries() {

            String query = "from Country";

            List<Country> countries = (List<Country>) hibernateTemplate.find(query, null);

            // print out
            for (Country c : countries) {
                System.out.print(c.getId() + " ");
                System.out.print(c.getCountry() + " ");
                System.out.print(c.getCapital() + " ");
                System.out.println(c.getContinent() + " ");
            }

            return countries;
        }

        @Override
        public List<Country> getCountriesByContinent(String continent) {

            String query = "from Country c where c.continent = :cntnt";

            List<Country> countries = (List<Country>) hibernateTemplate.findByNamedParam(query, "cntnt", continent);

            // print out
            for (Country c : countries) {
                System.out.print(c.getId() + " ");
                System.out.print(c.getCountry() + " ");
                System.out.print(c.getCapital() + " ");
                System.out.println(c.getContinent() + " ");
            }
            return countries;
        }

        @Override
        public Country getCountryByName(String country) {

            String query = "FROM Country c WHERE c.country = : cntry";
            Country countryResult = (Country) hibernateTemplate.findByNamedParam(query, "cntry", country);

            return countryResult;
        }

    }

ICountryDAO
    package com.pckg.dao;

    import java.util.List;

    import com.pckg.entity.Country;

    public interface ICountryDAO {

        public List<Country> getAllCountries();

        public List<Country> getCountriesByContinent(String continent);

        public Country getCountryByName(String country);
    }

国家
    package com.pckg.entity;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;

    @Entity
    @Table(name = "countries")
    public class Country {

        @Id
        @Column(name = "id")
        private int id;

        @Column(name = "country")
        private String country;

        @Column(name = "capital")
        private String capital;

        @Column(name = "continent")
        private String continent;

        // no arg constructor
        public Country() {

        }

        public Country(int id, String country, String capital, String continent) {
            super();
            this.id = id;
            this.country = country;
            this.capital = capital;
            this.continent = continent;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getCountry() {
            return country;
        }

        public void setCountry(String country) {
            this.country = country;
        }

        public String getCapital() {
            return capital;
        }

        public void setCapital(String capital) {
            this.capital = capital;
        }

        public String getContinent() {
            return continent;
        }

        public void setContinent(String continent) {
            this.continent = continent;
        }

    }

CountryService
    package com.pckg.service;

    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;

    import com.pckg.dao.ICountryDAO;
    import com.pckg.entity.Country;

    public class CountryService implements ICountryService {

        @Autowired
        private ICountryDAO countryDAO;

        @Override
        public List<Country> getAllCountries() {
            return countryDAO.getAllCountries();
        }

        @Override
        public List<Country> getCountriesByContinent(String continent) {
            return countryDAO.getCountriesByContinent(continent);
        }

        @Override
        public Country getCountryByName(String country) {
            return countryDAO.getCountryByName(country);
        }

    }

ICountryService
    package com.pckg.service;

    import java.util.List;

    import com.pckg.entity.Country;

    public interface ICountryService {

        public List<Country> getAllCountries();

        public List<Country> getCountriesByContinent(String continent);

        public Country getCountryByName(String country);
    }

应用程序
    package com.pckg.test;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    @SpringBootApplication
    public class Application {

        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }

    }

任何有关如何使我的代码正常工作的建议将不胜感激。谢谢!

编辑:

我将以下代码添加到gradle.build文件中:
    configurations.all {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
        exclude group: 'org.springframework.boot', module: 'logback-classic'
    }

它解决了原始问题,但运行“gradlew bootRun”后出现新错误
            [main] WARN org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
            [main] ERROR org.springframework.boot.SpringApplication - Application startup failed
            org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
                    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
                    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:536)
                    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
                    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
                    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
                    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
                    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186)
                    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175)
                    at com.pckg.test.Application.main(Application.java:10)
            Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
                    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:189)
                    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:162)
                    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134)
                    ... 8 more
            :bootRun FAILED

            FAILURE: Build failed with an exception.

我已经研究了这个问题,但是找不到解决此问题的方法。

最佳答案

您可以尝试在服务展示和界面上添加@Service。

关于ERR_CONNECTION_REFUSED,您的服务器是否正常运行?您可以发布 Spring 启动日志吗? @Entity和@RestController部分看起来不错,不确定dao。

我也建议您使用application.properties使用https://spring.io/guides/gs/accessing-data-jpa/连接到您的数据库。更干净,更快捷的体验。

关于java - 如何使Spring,Hibernate,RESTful Web服务和Gradle一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41683388/

相关文章:

jquery - 处理 Thymeleaf Spring MVC AJAX 表单及其错误消息的推荐方法

java - 我需要帮助理解这些说明。 --接口(interface)、多态----

java - Spring Thymeleaf 如何将复选框的值绑定(bind)到集合字段

java - 如何从 Spring boot 调用 SOAP 服务

java - 无法获取 JSON 中的嵌套对象列表

java - 在新版本的 Hibernate View 中打开 session

java - 传递给 java 中方法的对象适用于原始副本

java - 如何在Java中的javaPairRDD上使用aggregateByKey?

java - 触发 ComboBox 选择同一项目的事件

java - hibernate多对多防止子项删除