JPA many-to-many persist to join table

前端 未结 2 1821
遥遥无期
遥遥无期 2020-12-18 04:52

I have two table with many-to-many relations. I mapped this two entities when I am persisting users doesn\'t insert anything to join table. I am debugging till the persist,

2条回答
  •  有刺的猬
    2020-12-18 05:18

    For your first question about to show sql scripts, i've added this code in the persistence.xml

    
      
      
    
    

    After that, clean and build and then deploy. The sql executed by JPA will be displayed in the glassfish domain log of the netbeans.

    For your second issue about the many-to-many relationship.

    i was having the same issue in the same scenario, beacuse i've to implement web security and i need the same relationship you are using. Anyway, i figured out that the problem wasn't in the entities.

    You have to check (for my case) the insert and edit methods on the UserJPAController.java, those methods some how knows how the entities are referenced each other, so i implemented this code and it works fine.

    List attachedGrupoList = new ArrayList();
            for (Grupo grupoListGrupoToAttach : usuario.getGrupoList()) {
                grupoListGrupoToAttach = em.getReference(grupoListGrupoToAttach.getClass(),      grupoListGrupoToAttach.getIdGrupo());
                attachedGrupoList.add(grupoListGrupoToAttach);
            }
            usuario.setGrupoList(attachedGrupoList);
            em.persist(usuario);
    for (Grupo grupoListGrupo : usuario.getGrupoList()) {
                grupoListGrupo.getUsuarioList().add(usuario);
                grupoListGrupo = em.merge(grupoListGrupo);
            }
    

    After executing that code and the transaction has ended you will see the sql scripts executed by JPA in the Data Base.

    Hope it helps!

    Mike

提交回复
热议问题