Himalay Majumdar
Himalay Majumdar

Reputation: 3973

Hibernate creating relation on @JoinTable

I have two tables which have Many-to-Many relations which have a JoinTable USER_SERVICES as below.

@Entity
public class User implements Serializable {

    @NotNull
    @Column(unique=true)
    private String username;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "USER_SERVICES",
            joinColumns = {@JoinColumn(name = "id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "", referencedColumnName = "name")})
    private Set<Services> services;

    // Getters and Setters
}   


@Entity
public class Services implements Serializable {

    @NotNull
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private Long serviceId;

    @NotNull
    @Column(unique=true)
    private String name;

    //Getters and Setters

}

The above code creates a table USER_SERVICES, but I also want to have a Many-to-Many relation on the table USER_SERVICES with another table RATINGS which would result in another table USER_SERVICES_RATINGS. how can I define this relation with Hibernate/JPA annotations?

Upvotes: 0

Views: 669

Answers (2)

JamesENL
JamesENL

Reputation: 6540

Bi-Directional Many to Many using user managed join table object (Relatively common)

Commonly used when you want to store extra information on the join object such as the date the relationship was created.

public class Foo{
    private UUID fooId;

    @OneToMany(mappedBy = "bar", cascade=CascadeType.ALL)
    private List<FooBar> bars;
}

public class Bar{
    private UUID barId;

    @OneToMany(mappedBy = "foo", cascade=CascadeType.ALL)
    private List<FooBar> foos;
}

@Entity
@Table(name="FOO_BAR")
public class FooBar{
    private UUID fooBarId;

    @ManyToOne
    @JoinColumn(name = "fooId")
    private Foo foo;

    @ManyToOne
    @JoinColumn(name = "barId")
    private Bar bar;

    //You can store other objects/fields on this table here.
}

Upvotes: 3

Taylor
Taylor

Reputation: 4086

You need to create an explicit UserServices entity and setup the relationship to the Ratings entity per your needs.

Remember that in hibernate you model relationships between entities (i.e. your java objects), not db tables.

Upvotes: 1

Related Questions