How best to relate this entity

Asked

Viewed 39 times

2

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

I am 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 which classes he completed? i can take advantage of this many user relationship?

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

@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
}

1 answer

1


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

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 still would be not to use @ManyToMany. I suggest mapping the intermediate table, as 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’ll be worth it.

  • Thank you very much, I will search how to use an intermediary table.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.