在更改项目结构后,RequestMapping和Hibernate没有按预期工作

时间:2016-08-15 07:20:54

标签: java spring hibernate

我正在学习Java EE的Spring框架。

最近,我想构建一个以后端数据库支持作为数据源的restful服务。我搜索了很多关于如何找到一个有效的样本项目here的帖子。这篇文章很棒,我已经按照他的代码编写了一个正在运行的应用程序。

但在那之后,我决定拥有自己的项目结构,因为我将拥有超过5个模型和多个其他接口,所以我会更清楚。

这是他的项目结构。

├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── eu
│   │   │       └── christophburmeister
│   │   │           └── playground
│   │   │               ├── Application.java
│   │   │               ├── IMovieRepository.java
│   │   │               ├── RestServiceController.java
│   │   │               └── models
│   │   │                   ├── Movie.java
│   │   │                   └── Stock.java
│   │   └── resources
│   │       ├── application.properties
│   │       └── log4j2.xml
│   └── test
│       ├── java
│       └── resources

这是我的。

├── README.md
├── pom.xml
├── q_image
│   ├── his.png
│   └── mine.png
├── src
│   ├── main
│   │   ├── java
│   │   │   ├── application
│   │   │   │   └── Application.java
│   │   │   ├── controllers
│   │   │   │   └── RestServiceController.java
│   │   │   ├── models
│   │   │   │   └── Stock.java
│   │   │   └── repositories
│   │   │       └── IStockRepository.java
│   │   └── resources
│   │       ├── application.properties
│   │       └── log4j2.xml

我检查了两个应用程序(他和我的)并且他的版本有效,但我没有。有配置/属性文件,但它们都是相同的,不包括任何文件路径配置。

这是他的应用程序控制台中的结果。我已经知道哪些部分与我的不同,但我不知道如何解决它。对不起,日志很长,但我会告诉你不同的行。

它们是从15:09:58.36415:09:58.371的行。看起来我的hibernate并没有将我的模型映射到我的数据库中。我没有这些行。

4行以15:09:59.013开头。看起来URL没有正确映射。我没有这些行。

其余的日志几乎相同。

15:09:52.331 [main] INFO  eu.christophburmeister.playground.Application - entered application

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.1.RELEASE)

15:09:52.960 [main] INFO  eu.christophburmeister.playground.Application - Starting Application on Jis-MacBook-Pro.local with PID 3216 (/Users/Kulbear/Documents/workspace/springboot-rest/target/classes started by Kulbear in /Users/Kulbear/Documents/workspace/springboot-rest)
15:09:52.960 [main] INFO  eu.christophburmeister.playground.Application - No active profile set, falling back to default profiles: default
15:09:53.057 [main] INFO  org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@15eb5ee5: startup date [Mon Aug 15 15:09:53 CST 2016]; root of context hierarchy
15:09:53.337 [pool-2-thread-1] INFO  org.hibernate.validator.internal.util.Version - HV000001: Hibernate Validator 5.2.2.Final
15:09:54.179 [main] INFO  org.springframework.beans.factory.support.DefaultListableBeanFactory - Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
15:09:54.801 [main] INFO  org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$fe0bb32b] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
15:09:55.379 [main] INFO  org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat initialized with port(s): 8080 (http)
15:09:55.398 [main] INFO  org.apache.catalina.core.StandardService - Starting service Tomcat
15:09:55.402 [main] INFO  org.apache.catalina.core.StandardEngine - Starting Servlet Engine: Apache Tomcat/8.0.30
15:09:55.532 [localhost-startStop-1] INFO  org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
15:09:55.532 [localhost-startStop-1] INFO  org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 2479 ms
15:09:55.918 [localhost-startStop-1] INFO  org.springframework.boot.context.embedded.ServletRegistrationBean - Mapping servlet: 'dispatcherServlet' to [/]
15:09:55.925 [localhost-startStop-1] INFO  org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'characterEncodingFilter' to: [/*]
15:09:55.926 [localhost-startStop-1] INFO  org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
15:09:55.926 [localhost-startStop-1] INFO  org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'httpPutFormContentFilter' to: [/*]
15:09:55.926 [localhost-startStop-1] INFO  org.springframework.boot.context.embedded.FilterRegistrationBean - Mapping filter: 'requestContextFilter' to: [/*]
15:09:56.360 [main] INFO  org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'default'
15:09:56.388 [main] INFO  org.hibernate.jpa.internal.util.LogHelper - HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
15:09:56.552 [main] INFO  org.hibernate.Version - HHH000412: Hibernate Core {4.3.11.Final}
15:09:56.554 [main] INFO  org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found
15:09:56.557 [main] INFO  org.hibernate.cfg.Environment - HHH000021: Bytecode provider name : javassist
15:09:56.921 [main] INFO  org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Mon Aug 15 15:09:57 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Aug 15 15:09:57 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Aug 15 15:09:57 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Aug 15 15:09:57 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Aug 15 15:09:57 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Aug 15 15:09:57 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Aug 15 15:09:57 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Aug 15 15:09:57 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Aug 15 15:09:57 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Aug 15 15:09:57 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
15:09:57.700 [main] INFO  org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
15:09:57.907 [main] INFO  org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory - HHH000397: Using ASTQueryTranslatorFactory
15:09:58.340 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000228: Running hbm2ddl schema update
15:09:58.340 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000102: Fetching database metadata
15:09:58.342 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000396: Updating schema
15:09:58.364 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - HHH000261: Table found: playground.movie
15:09:58.364 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - HHH000037: Columns: [year, id, title]
15:09:58.364 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - HHH000108: Foreign keys: []
15:09:58.364 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - HHH000126: Indexes: [primary]
15:09:58.371 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - HHH000261: Table found: playground.stock
15:09:58.371 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - HHH000037: Columns: [year, name, id, title]
15:09:58.371 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - HHH000108: Foreign keys: []
15:09:58.371 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata - HHH000126: Indexes: [primary]
15:09:58.372 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000232: Schema update complete
15:09:58.913 [main] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@15eb5ee5: startup date [Mon Aug 15 15:09:53 CST 2016]; root of context hierarchy
15:09:59.012 [main] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/movies/create]}" onto public java.lang.String eu.christophburmeister.playground.RestServiceController.createMovie(java.lang.String,int)
15:09:59.013 [main] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/movies/update]}" onto public java.lang.String eu.christophburmeister.playground.RestServiceController.readMovie(long,java.lang.String,int)
15:09:59.013 [main] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/movies/read]}" onto public java.lang.String eu.christophburmeister.playground.RestServiceController.readMovie(long)
15:09:59.013 [main] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/movies/delete]}" onto public java.lang.String eu.christophburmeister.playground.RestServiceController.deleteMovie(long)
15:09:59.013 [main] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/movies/readAllBeforeYear]}" onto public java.util.List<eu.christophburmeister.playground.models.Movie> eu.christophburmeister.playground.RestServiceController.getMoviesBeforeYear(int)
15:09:59.015 [main] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
15:09:59.016 [main] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
15:09:59.046 [main] INFO  org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
15:09:59.046 [main] INFO  org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
15:09:59.087 [main] INFO  org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
15:09:59.372 [main] INFO  org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Registering beans for JMX exposure on startup
15:09:59.410 [main] INFO  org.apache.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-8080"]
15:09:59.421 [main] INFO  org.apache.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8080"]
15:09:59.446 [main] INFO  org.apache.tomcat.util.net.NioSelectorPool - Using a shared selector for servlet write/read
15:09:59.465 [main] INFO  org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat started on port(s): 8080 (http)
15:09:59.471 [main] INFO  eu.christophburmeister.playground.Application - Started Application in 7.008 seconds (JVM running for 8.175)

为了明确引用我的控制器中的代码如下所示,唯一更改的部分是moviestock

package controllers;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import models.Stock;
import repositories.IStockRepository;

@RestController
public class RestServiceController {

    @Autowired
    private IStockRepository repo;

    static final Logger logger = LogManager.getLogger(RestServiceController.class.getName());

    // CREATE
    @RequestMapping("/stocks/create")
    @ResponseBody
    public String createStock(String name) {
        Stock stock = new Stock(name);
        try {
            repo.save(stock);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return e.getMessage();
        }
        return "Creation successful: " + String.valueOf(stock.getId());
    }
}

我尝试了http://localhost:8080/stocks/create?name=abc并且说

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Aug 15 14:44:27 CST 2016
There was an unexpected error (type=Not Found, status=404).
No message available

我的项目位于here

这是一个很长的描述和错误报告的问题。感谢您的帮助和时间。

编辑: 如果您认为它会有所帮助,请pom.xml。但唯一不同的部分是groupIdartifactId

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>sczq.portfolio</groupId>
    <artifactId>sczq-portfolio</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
    </parent>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <!-- we want to rely on external log4j2 -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-ws</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- JPA -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- logging -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
    </dependencies>

</project>

1 个答案:

答案 0 :(得分:0)

Application.java是Spring启动应用程序的主要入口,使用@SpringBootApplication进行注释。该注释会自动应用许多其他配置,例如控制器,存储库,实体等的基础包。

在示例应用程序中,所有类(存储库,实体,控制器等)都位于Application.java的相同目录或子目录中,这有助于正确配置应用程序。现在,由于您已将Application.java移动到独立程序包,因此Application.java不会显示控制器,存储库等,因为它们不再可见。

您需要手动配置它们,使用Application.java上的注释或重新构建项目,以便其他所有内容直接位于Application.java的子目录中。

通常,我更喜欢将Application.java保留在默认包中。这让生活变得更加轻松。