Reputation: 15
I have 2 entites User
and Role
with many to many relationship. I want to get role_id
for specific user_id
.
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToMany
private Set<Role> roles;
}
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany(mappedBy = "roles")
private Set<User> users;
}
@Override
public List<Long> getUserRole(User user) {
return entityManager.createNativeQuery("??????").getResultList();
}
How should I write query in JPA?
Upvotes: 0
Views: 45
Reputation: 2303
First if you use createNativeQuery then you'll supply a native SQL query. If you want to use JPQL use the createQuery
To select the role_id by user id do
select role.id from Role role join role.users user where user.id=:p1
After that, you can do
entityManager.createQuery("query").setParameter("p1", user.getId()).getResultList();
Upvotes: 1