Search code examples
javaspringhibernatejpapolymorphism

@OneToMany has an error: mappedBy reference an unknown target entity property


My model consists of different types of Budgets. These Budgets have different Attributes. I want to make a OneToMany Relationship between these different types of Budgets. So lets say I have BudgetLevel1 that has many BudgetLevel2, which again has many BudgetLevel3. All these BudgetLevels extend the Class Budget

My Budget Class

@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Budget {

@Id
private Long id;
private String name;
private BudgetTyp budgetTyp;
private Double amount;

BudgetLevel1 Class

@Entity(name= "BudgetLevel1 ")
public class BudgetLevel1 extends Budget {

@OneToMany(
            **mappedBy="attBudgetLevel2 ",**
            cascade=CascadeType.ALL,
            orphanRemoval=true
            )
private List<BudgetLevel2> budgets= new ArrayList<>();
private String att1;

BudgetLevel2 Class

@Entity(name= "BudgetLevel2")
public class BudgetLevel2 extends Budget {

@OneToMany(
            mappedBy="budgetlevel2",
            cascade=CascadeType.ALL,
            orphanRemoval=true
            )
private List<BudgetLevel3> budgets= new ArrayList<>();

**@ManyToOne( fetch=FetchType.LAZY,
        cascade=CascadeType.PERSIST)
@JoinColumn(name="budget_id")
Private BudgetLevel2 attBudgetLevel2;**

private String att2;

Budgetlevel3 would look similar

this is the error I get

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.bm.ent.geschaeftsfeld.marke.BudgetLevel2.budgetlevel1 in com.bm.ent.geschaeftsfeld.BudegetLevel1.budgetlevel2 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786) ~[spring-beans-5.3.9.jar:5.3.9]

org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.5.4.jar:2.5.4] Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.bm.ent.geschaeftsfeld.marke.BudgetLevel2.budgetlevel1 in com.bm.ent.geschaeftsfeld.BudegetLevel1.budgetlevel2


Solution

  • mappedBy works by referencing the actual field names. As you write mappedBy="budgetlevel2", you tell hibernate to look for a field named budgetlevel2, which you don't have.

    You need to reference the field name directly and to make sure that you have hibernate look in the right entity, also specify the targetEntity like this:

    @OneToMany(
                mappedBy="budgets",
                cascade=CascadeType.ALL,
                orphanRemoval=true,
                targetEntity = BudgetLevel2.class
                )