我有两个具有多对多关系的表,它们具有如下的 JoinTable USER_SERVICES。
@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
}
上面的代码创建了一个表 USER_SERVICES,但我还希望在表 USER_SERVICES 上与另一个表 RATINGS 建立多对多关系,这将导致另一个表 USER_SERVICES_RATINGS。如何使用 Hibernate/JPA 注释定义这种关系?
最佳答案
使用用户管理的连接表对象进行双向多对多(相对常见)
当您想要存储有关连接对象的额外信息(例如创建关系的日期)时通常使用。
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.
}
关于java - Hibernate 在 @JoinTable 上创建关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24522090/