java - 更改项目结构后,RequestMapping 和 Hibernate 无法按预期工作

标签 java spring hibernate

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

最近,我想构建一个以后端数据库支持作为数据源的 Restful 服务。我搜索了很多关于如何并最终找到一个有效的示例项目的帖子 here 。这篇文章很棒,我遵循了他的代码并制作了一个正在运行的应用程序。

但在那之后,我决定拥有自己的项目结构,该结构更加清晰,因为我将拥有超过 5 个模型和多个其他接口(interface)。

这是他的项目结构。

├── 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)

为了清楚地引用,我的 Controller 中的代码如下所示,唯一更改的部分是将 movie 更改为 stock

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>

最佳答案

Application.java是Spring Boot应用程序的主入口,用@SpringBootApplication注解。该注释会自动应用许多其他配置,例如 Controller 、存储库、实体等的基础包。

在示例应用程序中,所有类(存储库、实体、 Controller 等)都位于 Application.java 的同一目录或子目录中,这有助于正确配置应用程序。现在,由于您已将 Application.java 移至独立包,因此不再扫描 Controller 、存储库等,因为它们对 Application.java 不可见。

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

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

关于java - 更改项目结构后,RequestMapping 和 Hibernate 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38950847/

相关文章:

java - 使用ViewPager后TabItem图标消失

java - 无法导入库 libcore.io.IoBridge

java - Spring-Boot 的最终目标

java - 如何使用hibernate在spring boot中调用MySQL存储过程?

java - spring boot 无法连接到 mySql

java - CardLayout 显示下一个面板 - java Swing

java - MySQL 5.5.9 和 TYPE 上的 Hibernate 表创建错误

java - REST spring 服务和 JQUERY Web 集成最佳实践

java - 在 MySQL 集群上使用 JPA/Hibernate 检查外键约束

java - Spring中entityManager上的NullPointerException