user15425589
user15425589

Reputation:

I am getting error in OneToMany relations?

I am trying to make a relation between two entities, but the one of them is inherited. So i have a Classroom class:

@Entity
public class Classroom {

    @Id
    private int number;
    private int floor;
    @OneToMany(mappedBy = "room")
    private List<Teacher> teachers;

}

and Teacher class, which extends Employee:

@Entity
@Table(name="teachers")
@NoArgsConstructor
@AllArgsConstructor
public class Teacher extends Employee{

    private int lessons;
    @ManyToOne
    private Classroom room;
    
}

I get the following error, when I try to run this code:

mappedBy reference an unknown target entity property: com.example.demo.entities.Teacher.room in com.example.demo.entities.Classroom.teachers

Upvotes: 2

Views: 52

Answers (2)

Giorgi Tsiklauri
Giorgi Tsiklauri

Reputation: 11136

mappedBy reference an unknown target entity property

gives us some idea on what is going wrong.

Your POJOs should be @Entitys, in order to be enabled as persistent classes; therefore, you should annotate your Teacher class with @Entity, like this:

@Entity
public class Teacher extends Employee {

    //you might also consider having PK

    private int lessons;
    
    @ManyToOne
    private Classroom room;

}

Beware!, that if your super-class (that is Employee) has some persistent state, it will not be enabled to the JPA for being ORM-ed, by default, on its own. For the latter purpose, you will need @MappedSuperclass on top of your super-class definition.

Upvotes: 2

Guillaume
Guillaume

Reputation: 14671

Your Teacher class needs to be declared as an entity:

@Entity
public class Teacher extends Employee

If you're using hibernate.cfg.xml you'll also need to declare the Teacher class there:

<mapping class="com.example.demo.entities.Teacher"/>

Upvotes: 1

Related Questions