I have a many-to-many relation in my project and although I'm able to write in my two Entities table, the relational table does not get anything written.
Here's how I'm declaring this using JPA annotations:
Professor.java
@Entity
@Table(name = "Professor")
public class Professor implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "idProfessor", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "ALUNO_PROFESSOR",
joinColumns = @JoinColumn(name = "idProfessor", referencedColumnName = "idProfessor"),
inverseJoinColumns = @JoinColumn(name = "idAluno", referencedColumnName = "idAluno"))
private List<Aluno> alunoList;
// getters and setters
}
Aluno.java
@Entity
@Table(name = "Aluno")
public class Aluno implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "idAluno", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToMany(mappedBy = "alunoList", fetch = FetchType.EAGER)
private List<Professor> professorList;
// getters and setters
}
And here is the service layer to insert into database:
@Autowired
private AlunoDao alunoDao;
@Autowired
private ProfessorDao professorDao;
@RequestMapping(value = RestUriConstants.SUBMETER, method = RequestMethod.POST)
public @ResponseBody JsonResponse submeter(@RequestBody final Aluno aluno) {
Professor professor = professorDao.find(1);
aluno.setProfessorList(Arrays.asList(professor));
alunoDao.persist(aluno);
...
}
In this case, please consider that I already have an entry with id "1" for Professor.
As I said, it does write on Aluno and Professor table but does NOT write anything into ALUNO_PROFESSOR table.
I've already taken a look at these three kind of similiar questions but none of them could help me:
Hibernate and Spring: value of many-to-many not inserted into generated table
JPA many-to-many persist to join table
How to persist @ManyToMany relation - duplicate entry or detached entity
EDIT - Adding more code snippets
JpaAlunoDao.java
@Repository
public class JpaAlunoDao implements AlunoDao {
@PersistenceContext
private EntityManager em;
@Transactional
public void persist(Aluno aluno) {
em.persist(aluno);
}
}
JpaExercicioDao.java
@Repository
public class JpaExercicioDao implements ExercicioDao {
@PersistenceContext
private EntityManager em;
@Transactional
public void persist(Exercicio exercicio) {
em.persist(exercicio);
}
}