0

in my spring boot application I have a user entity that relates from many to many with the entity courses (one user can enroll in many courses and one course can have multiple users) And the entity courses relates one to many with the entity class (one course has several classes, but one class only has one course)

I'm doing my application with spring boot and for me to say that the user has enrolled in a course I just have to do:

user.setCourse(course)
userRepository.save(user)

when relating a course to the user I can say that he enrolled in the course. But how to relate the user to a class to know for example what classes he completed? I can take advantage of this user relationship too much for a lot of course one for many class or do I have to create a many relationship for many user with class?

Here is a small example of entities to better exemplify how the relationship is:

@Entity
public class User{

private long id;
private String name;
private String password;
@ManyToMany(mappedBy = “enrolledUser”, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable
private List enrolledCourse;

//getters and setters
}

@Entity
public class Course{

private long id;
private String name;
private String description;
@ManyToMany(mappedBy = “enrolledCourse”, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable
private List enrolledUser;
@OnetoMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List aulas;
//getters and setters
}

@Entity
public class Class{

private long id;
private String name;
private String content;
@ManyToOne(mappedBy = “class”, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable
private Course course;
//getters and setters
}
Davi Resio
  • 653
  • 2
  • 11
  • 21

1 Answers1

1

There are many things wrong here. First of all you cannot do this:

user.setCourse(course) userRepository.save(user)

because we are talking about a many-to-many relationship. You would do something like this:

user.courses.add(course)

and vice versa

course.users.add(user)

Then you can save the user. Please follow the tutorial here:

https://www.callicoder.com/hibernate-spring-boot-jpa-many-to-many-mapping-example/

And use generic lists like List<Course> instead of just List. Actually I recommend using Set<Course> in this case. Just follow the tutorial above.

You can define the Class as a join table with extra columns that you need. Have a look at this post for defining those extra columns:

JPA 2.0 many-to-many with extra column

humbaba
  • 318
  • 2
  • 10
  • this is a good tutorial, thank you very much. i will study now about extra column because its is new for me – Davi Resio Apr 20 '18 at 17:41