JPA doubts @ManyToMany matching

Hi I am learning about mapping @ManyToMany relationships using JPA. I more or less understand how it works, but I have doubts. Let me show you this code first, where I am doing 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 object:

@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

My doubts:

-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 only one proxy table EntityB_EntityF is supposed to be created. But for some reason it creates a second table called EntityF_EntityE. I do not understand why? This is normal? and if not, how to fix it?

+3


source to share


1 answer


Ok, I got the answer after a little experiment. I think this is correct, now it works as I used. What I did was add a name for the relationship because for some strange reason, if you don't provide a name, it creates a bi-directional 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's another object.



@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, I managed to resolve my doubts. I hope this answer might be helpful for someone else as well.

enter image description here

+2


source