SELECT * FROM with JPA for many-to-many relationship

时间:2018-01-15 04:04:18

标签: java sql hibernate jpa jpql

我想使用JPQL进行内部联接的查询(SELECT)。 我正在使用 hibernate ddl auto 从实体创建表。

我有两个实体,它们通过多对多关系在它们之间进行关联(一个工作室可以由许多管理员(用户)管理,一个管理员(用户)可以管理许多工作室 )。

如您所知,对于多对多关系,我们使用中间表对本机SQL执行“SELECT”,但我使用JPA和JPQL作为查询语言,所以我的问题是:如何通过多对多关系在两个表之间进行JOIN SELECT连接?

以下实体是我的实体:

实体1(工作室):

@Entity
@Table(name = "studio")
public class Studio implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@Column(name = "studio_name", nullable = false)
private String studioName;

/**
 * Indicates if the studio is active or inactive in the data base.
 */
@Column(name = "active")
private Boolean active;

/**
 * The studio owner is the main manager for a studio.
 */
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "studio_owner", referencedColumnName = "id", nullable = false)
private User studioOwner;

/**
 * Represents all the possible managers for this studio.
 */
@ManyToMany(fetch = FetchType.LAZY)
private List<User> studioManagers;

//--Getters and setter below
}

实体2(用户):

@Entity
@Table(name = "userr")
public class User implements Serializable  {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column(name = "user_name", nullable = false, unique = true)
private String userName;

@Column(name = "email", nullable = false, unique = true)
private String email;

@Column(name = "password", length = 60)
private String password;

@Column(name = "name")
private String name;

@Column(name = "last_name")
private String lastName;

@Column(name = "user_state", nullable = false)
@Enumerated(EnumType.STRING)
private UserState userState; 

/**
 * The roles for this user.
 */
@ManyToMany(fetch = FetchType.EAGER)
private List<Role> roles;

public User() {
}

//--Getters and setter below
}

我很抱歉英语,我是西班牙语。

1 个答案:

答案 0 :(得分:0)

在StudioRepository.java中只需编写一个方法

List<Studio> findById(Integer id); 

这将获取与该工作室相关的所有用户的工作室。

例如: 工作室{   &#34; id&#34;:1,   &#34; studioName&#34;:&#34; some&#34;,   &#34; studioOwner&#34;:[     {       .....       ....     },     {       ....     }   ] }