How best to relate this entity

2

In my 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:

usuario.getCursos().add(curso)
curso.getUsuario().add(usuario)
usuarioRepository.save(usuario)

By 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 Usuario{

private long id;
private String nome;
private String senha;
@ManyToMany(mappedBy = “usuariosMatriculados”, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable
private List cursosMatriculados;

//getters and setters
}

@Entity
public class Curso{

private long id;
private String nomeCurso;
private String descricaoCurso;
@ManyToMany(mappedBy = “cursosMatriculados”, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable
private List usuariosMatriculados;
@OnetoMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List aulas;
//getters and setters
}

@Entity
public class Aula{

private long id;
private String nomeAula;
private String conteudoAula;
@ManyToOne(mappedBy = “aulas”, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable
private Curso curso;
//getters and setters
}
    
asked by anonymous 20.04.2018 / 19:09

1 answer

1

It seems to me that the best case is to have a many-to-many relationship between User and Classroom. I understand that this relationship is independent of the Course.

In this way, you would have:

class Usuario {

    @ManyToMany
    private List<Curso> cursos;

    @ManyToMany
    private List<Aula> aulas;

}

class Aula {

    @ManyToMany
    private List<Usuario> usuario;

    @ManyToOne
    private Curso curso;

}

class Curso {

    @ManyToMany
    private List<Usuario> usuario;

    @ManyToMany
    private List<Aula> aulas;

}

My recommendation would still be to not use @ManyToMany . I suggest mapping the middle table because it gets less "magical" and eventually you will feel the need to add information in this relationship table. I end up getting more verbose, but I think it will be worth it.

    
20.04.2018 / 20:17