Use of @OneToMany or @ManyToMany targeting an unmapped class exception occuring

倾然丶 夕夏残阳落幕 提交于 2021-02-11 15:33:59

问题


I am creating my first Spring-Boot-Starter-data-jpa project. I was following a tutorial on that and creating a separate application in same way. When I am starting my Spring Boot application , I am getting

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class.

I have already checked few answers for the same issue and tried to resolve but still getting same error. Please help as i am clueless here. I have mainly two entities , student and PaymentRecord. One student can have multiple PaymentRecords.

Student Class

package org.springboot.schoolmanagement.Entity;
import java.util.HashMap;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import com.school.management.system.Payment.PaymentRecord;
@Entity
@Table(name= "student")
public class Student {
    @Id
    private int  id;
    private String name;
    private int age;
    private int grade;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "student")
    public Set<PaymentRecord>  payments = null;//


    public Set<PaymentRecord> getStudenPayments() {
        return payments;
    }


    public int getGrade() {
        return grade;
    }
    public void setGrade(int grade) {
        this.grade = grade;
    }
    public String getName() {
        return name;
    }
    public Student(int id, String name, int age, int grade) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.grade = grade;
        }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }



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

PaymentRecord.java

package org.springboot.schoolmanagement.Entity;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "payments")
public class PaymentRecord {
    @Id
    private int paymentId;
    @ManyToOne
    @JoinColumn(name = "id")
    private Student student;
    private String month;
    private int amount;

    public PaymentRecord() {

    }

    public int getPaymentId() {
        return paymentId;
    }

    public void setPaymentId(int paymentId) {
        this.paymentId = paymentId;
    }


    public String getMonth() {
        return month;
    }
    public void setMonth(String month2) {
        this.month = month2;
    }
    public int getAmount() {
        return amount;
    }
    public void setAmount(int amount) {
        this.amount = amount;
    }

}

Pom.xml

<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>SchoolFinanceManagement</groupId>
  <artifactId>SchoolManagement</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>SchoolFeesPaymentManagement</name>
  <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.4.2.RELEASE</version>
</parent>

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

     <!-- This is the only dependency required to enable our web application connect to the datbase -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
<!-- This is the only dependency required to enable our web application connect to the datbase -->      

     <!--  this is for for downloading the database to which our application connects -->
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <scope>runtime</scope>
        </dependency>

<!--  this is for for downloading the database to which our application connects -->        


    </dependencies>


  <properties>
     <java.version>1.8</java.version>
  </properties>
</project>

Console log and stack trace:


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

2020-06-10 11:25:57.789  INFO 14744 --- [           main] o.s.schoolmanagement.Application         : Starting Application on DESKTOP-EL3JT6U with PID 14744 (C:\Users\HP\JavaBasicProjects\SchoolManagement\target\classes started by HP in C:\Users\HP\JavaBasicProjects\SchoolManagement)
2020-06-10 11:25:57.813  INFO 14744 --- [           main] o.s.schoolmanagement.Application         : No active profile set, falling back to default profiles: default
2020-06-10 11:25:58.195  INFO 14744 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@57c758ac: startup date [Wed Jun 10 11:25:58 PDT 2020]; root of context hierarchy
2020-06-10 11:26:05.777  INFO 14744 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$1f7adbdb] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-06-10 11:26:07.927  INFO 14744 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2020-06-10 11:26:07.973  INFO 14744 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2020-06-10 11:26:07.975  INFO 14744 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6
2020-06-10 11:26:08.342  INFO 14744 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-06-10 11:26:08.351  INFO 14744 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 10148 ms
2020-06-10 11:26:08.860  INFO 14744 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2020-06-10 11:26:08.880  INFO 14744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2020-06-10 11:26:08.894  INFO 14744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2020-06-10 11:26:08.895  INFO 14744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2020-06-10 11:26:08.895  INFO 14744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2020-06-10 11:26:14.198  INFO 14744 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2020-06-10 11:26:14.959  INFO 14744 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2020-06-10 11:26:17.614  INFO 14744 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.11.Final}
2020-06-10 11:26:17.622  INFO 14744 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2020-06-10 11:26:17.629  INFO 14744 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2020-06-10 11:26:18.978  INFO 14744 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2020-06-10 11:26:25.233  INFO 14744 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.DerbyTenSevenDialect
2020-06-10 11:26:28.854  WARN 14744 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: org.springboot.schoolmanagement.Entity.Student.payments[com.school.management.system.Payment.PaymentRecord]
2020-06-10 11:26:28.897  INFO 14744 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2020-06-10 11:26:29.373  INFO 14744 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2020-06-10 11:26:29.409 ERROR 14744 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: org.springboot.schoolmanagement.Entity.Student.payments[com.school.management.system.Payment.PaymentRecord]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springboot.schoolmanagement.Application.main(Application.java:10) [classes/:na]
Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: org.springboot.schoolmanagement.Entity.Student.payments[com.school.management.system.Payment.PaymentRecord]
    at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1191) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:794) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:719) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:54) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1655) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1623) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373) ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:362) ~[spring-orm-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    ... 16 common frames omitted


回答1:


The Problem is incorrect import statement:

in your Student class change this line:

import com.school.management.system.Payment.PaymentRecord;

to this one:

import org.springboot.schoolmanagement.Entity.PaymentRecord;



回答2:


Using Bidirectional @OneToMany

Student Class

package org.springboot.schoolmanagement.Entity;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name= "student")
public class Student {
    @Id
    private int  id;
    private String name;
    private int age;
    private int grade;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "student",orphanRemoval = true)
    public Set<PaymentRecord>  payments = new HashSet();//

    //Constructors, getters and setters removed for brevity

    public void addPayment(PaymentRecord paymentRecord) {
        payments.add(paymentRecord);
        paymentRecord.setStudent(this);
    }

    public void removePayment(PaymentRecord paymentRecord) {
        payments.remove(paymentRecord);
        paymentRecord.setStudent(null);
    }       

}

PaymentRecord.java

package org.springboot.schoolmanagement.Entity;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "payments")
public class PaymentRecord {
    @Id
    private int paymentId;
    @ManyToOne(fetch = FetchType.LAZY)
    private Student student;
    private String month;
    private int amount;

    //Constructors, getters and setters removed for brevity
}

I hope this will be helpful.



来源:https://stackoverflow.com/questions/62307824/use-of-onetomany-or-manytomany-targeting-an-unmapped-class-exception-occuring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!