2
Good afternoon, I am creating a very simple Restful API that implements an online course system, where I have only 2 tables "Courses" and "Teachers" (And I am trying to learn Latin in the process):
I managed to make everything work right until I need to do an Inner Join between the 2 tables, now I can’t return the values... I wanted something like:
Teacher class
@Entity
public class Teacher {
@Id
@Column(name="teacher_id")
private int id;
@Column(name="teacher_name")
private String name;
@Column(name="teacher_phone")
private String phoneNumber;
private List<Course> courses;
public Teacher() {
courses = new ArrayList<>();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
@OneToMany(mappedBy="teacher")
public List<Course> getCourses() {
return courses;
}
}
Course class
@Entity
public class Course {
@Id
@Column(name="course_id")
private int id;
@Column(name="course_name")
private String name;
@Column(name="course_schedule")
private String schedule;
private Teacher teacher;
public Course() {
}
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name="teacher_id")
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSchedule() {
return schedule;
}
public void setSchedule(String schedule) {
this.schedule = schedule;
}
}
Database Access Class that would query
public interface CoursesRepository extends CrudRepository<Course, Integer>{
@Query("select c.course_id, c.course_name, c.course_schedule, t.teacher_name "
+ "from course c "
+ "inner join teacher t "
+ "on c.teacher_id = t.teacher_id")
public List<Course> findAllCoursesAndTeachers();
}
I’m getting an error that Spring can’t create the bean for my class, but I think it’s a problem with my relationships and/or my query (In the example query I showed I only had the name of the teacher, but I would have no problem if I brought the whole object) :
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.List, at table: teacher, for columns: [org.hibernate.mapping.Column(courses)]
That means I shouldn’t have the course list in the teacher class?
Thanks in advance.
Thanks Gustavo!! I will test here
– user94991
everything went well here, thank you very much!!
– user94991
Great, imagine.
– Gustavo