如何使所有软件包对Hibernate可见?

时间:2018-10-21 01:57:50

标签: java hibernate maven spring-boot

我正在使用Spring引导框架制作Maven应用程序。我还使用Hibernate ORM技术通过Postgres将对象持久化到数据库中。我遇到的一个问题是Unknown entity: ca.mcgill.ecse321.model.Vehicle错误,因为Hibernate无法“看到”该类。下面的代码片段显示了我的类层次结构和pom.xml文件。有没有办法让Hibernate查找模型类? 我没有使用hibernate.cfg.xml文件。

Class hierarchy

Pom.xml

<groupId>com.example</groupId>
<artifactId>RideSharing-backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>RideSharing</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.6.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.3.6.Final</version>
    </dependency>
</dependencies>

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


</project>

1 个答案:

答案 0 :(得分:1)

有几件事:

  1. 您可以将pom的Hibernate依赖项作为JPA删除,因为默认情况下是Hibernate依赖项。因此,请删除以下内容:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.3.6.Final</version>
    </dependency>
    
  2. 如果您在ca.mcgill.ecse321的根包中包含主类,则@SpringBootApplication将自动配置您的实体。

  3. 如果您的主类不在根包中,则在主类中,然后通过注释扫描实体以放入您的包名:

    @EntityScan("ca.mcgill.ecse321.model")
    @SpringBootApplication
    public class MyApplication {
    
    }