JPA duda sobre el mapeo de @ManyToMany

Hi i am learning about @ManyToMany relationship mapping using JPA. I more or less understand how it works, but i have a doubt. Let me show you first this code where i do some mapping:

@Entity
public class EntityE implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long eId;
    @ManyToMany
    @JoinTable(joinColumns =
    @JoinColumn(name = "eId"), inverseJoinColumns =
    @JoinColumn(name = "fId"))
    private Collection<EntityF> entityFs;
    //...
}

Also see this other entity:

@Entity
public class EntityF implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long fId;    
    private Collection<EntityE> entityEs;
    //...
 }

This is what i get in the database:

enter image description here

Mis dudas son:

-I want to create a @ManyToMany relationship where EntityE is the owner of the relationship, is this approach correct?

-I want the relationship to be unidirectional, so it is supposed to create just one mediator table called EntityB_EntityF. But for some reason it creates also a second table called EntityF_EntityE. I dont understand why is that?,Is that normal? and if not how should i fix it?

preguntado el 10 de marzo de 12 a las 03:03

1 Respuestas

Ok i just got the answer after doing some little experiment.I think it is correct, it now works as i spected. What i did was, add a name for the relationship, because for some strange reason if you don't specify the name it creates a bidirectional relationship.

See this code fixed it:

@Entity
public class EntityE implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long eId;
    @ManyToMany
    @JoinTable(name="entitye_entityf",joinColumns =
    @JoinColumn(name = "eId"), inverseJoinColumns =
    @JoinColumn(name = "fId"))
    private Collection<EntityF> entityFs;

Here is the other entity.

@Entity
public class EntityF implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long fId; 
    @ManyToMany
    @JoinTable(name="entitye_entityf",joinColumns =
    @JoinColumn(name = "fId"), inverseJoinColumns =
    @JoinColumn(name = "eId"))
    private Collection<EntityE> entityEs;

So as you can see from the image, managed to solve my doubts. I hope this answer can be useful for someone else as well.

enter image description here

respondido 10 mar '12, 04:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.