简体   繁体   中英

Bi-directional Many to Many JPA

I having a hard time with JPA hopefully someone can help me.

I have 3 tables:

  • Rol (CPE_ROL)
  • TipoUsuario (GTV_TIPOUSU)
  • RolTipoUsuario (CPE_ROLTUS - Join Table)

Rol.java

@JoinTable(name = "CPE_ROLTUS", joinColumns = {
    @JoinColumn(name = "CPE_ROLTUS_TIPOUSU_ID", referencedColumnName = "GTV_TIPOUSU_ID")}, inverseJoinColumns = {
    @JoinColumn(name = "CPE_ROLTUS_ROL_ID", referencedColumnName = "CPE_ROL_ID")})
@ManyToMany(fetch = FetchType.LAZY, cascade={CascadeType.REFRESH})
private List<TipoUsuario> tipoUsuarioList;

TipoUsuario.java

@ManyToMany(mappedBy = "tipoUsuarioList", fetch = FetchType.LAZY, cascade={CascadeType.REFRESH})


private List<Rol> rolesDefault;

For some reason rolesDefault is never filled up, I wondering if I'm missing something.

Thanks in advance.

Daniel

My guess is when you create the objects you are not setting both sides of the relationship. You must maintain bi-directional relationships in JPA. When you add to one side, also add to the other.

See, http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Object_corruption.2C_one_side_of_the_relationship_is_not_updated_after_updating_the_other_side

You most likely have caching enabled, or are using the same EntityManager, so when reading you get objects from the cache. You could also disable the shared cache, or refresh the object, but fixing your persist code is best.

Otherwise, enable logging on finest and see what SQL is executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM