简体   繁体   中英

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

I want to do a query(SELECT) with inner join using JPQL. I'm using hibernate ddl auto to create tables from the entities.

I have 2 entities, they're relacionated among them by many-to-many relationship( One studio can be managed by many managers(user) and one manager(user) can manage many studios ).

As you know, for many-to-many relationship, we use an intermediate table to do a "SELECT" with native SQL, but i'm using JPA and JPQL as query lenguage, so my question is: How to do JOIN SELECT between 2 tables relacionated among them by many-to-many relationship?

The entities below are my entities:

Entity 1(Studio):

@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
}

Entity 2(User):

@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
}

I'm sorry by me English, Im Spanish speaker.

In StudioRepository.java just write one method

List<Studio> findById(Integer id); 

this will fetch studio with all the users associated with this studio.

eg: Studio{ "id": 1, "studioName": "some", "studioOwner": [ { ..... .... }, { .... } ] }

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