简体   繁体   中英

Hibernate @ManyToMany multiple entities

I have the following scenario: Base Domain class:

@MappedSuperclass
public class BaseDomain {

    @Id
    protected UUID id;
}

Media Object class:

@Entity
public class MediaObject extends BaseDomain {

    @ManyToMany
    @JoinTable(
        joinColumns = { 
            @JoinColumn(name = "BaseDomain_id", referencedColumnName = "id" 
        }
        inverseJoinColumns = {
            @JoinColumn(name = "Media_id", referencedColumnName = "id")
        }
    private List<BaseDomain> holders;

}

"Holder" A:

@Entity
public class A extends BaseDomain {

    @ManyToMany
    private List<MediaObject>    media;
}

"Holder" B:

@Entity
public class B extends BaseDomain {

    @ManyToMany
    private List<MediaObject>     media;
}

What I want to achive is, to store a MediaObject and multiple entities may "hold" this object. My approach would be a using a JoinTable that stores the relation between the MediaObject and an arbitrary BaseDomain object (as above). The issue I'm facing is that the persistence provider (in my case Hibernate) would not be able to decide wich actual table to join. I'm thinking about using a unidirectional @OneToMany wich is possible in JPA 2.1. However, I want to ask, if there are some kind of best practices to approach such a situation.

Following snippet is used by me in production environement, it implements ManyToMany assiciation mapping for Hibernate.

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "printed_mails_logo",
        joinColumns = {
                @JoinColumn(name = "mails_id", nullable = false, updatable = false)
        },
        inverseJoinColumns = {
                @JoinColumn(name = "logo_id", nullable = false, updatable = false) })
private Set<Logo> printedLogos;
  1. printer_mails_logo is additinal associative table in database.
  2. @JoinColumn(name='x') is the actual name of column in associative table.

This works well for me. I can fetch without no problem all logos that has been printed already.

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