[英]retrieving data from many to many extra column in spring jpa uisng an id
I have user entity and category entity and they are as followed.One user can subscribe to many categories and similarly same category can be subscribed by many users.我有用户实体和类别实体,它们如下所示。一个用户可以订阅多个类别,同样的同一类别可以被多个用户订阅。
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long userId;
@NotBlank(message = "username can't be blank")
private String username;
@Email
@NotEmpty(message = "Email is required")
@Column(unique=true)
private String email;
@NotBlank(message = "Password is required")
private String password;
// Each user is going to be mapped to a Location
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(
name = "location_id",
referencedColumnName = "locationId"
)
@NotNull
private Location location ;
@EqualsAndHashCode.Exclude
@ToString.Exclude
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
@JoinTable(name = "users_categories",
joinColumns = {
@JoinColumn(name = "user_id", referencedColumnName = "userId",
nullable = false, updatable = false)},
inverseJoinColumns = {
@JoinColumn(name = "category_id", referencedColumnName = "categoryId",
nullable = false, updatable = false)})
private Set <Categories> categories = new HashSet<>();
}
And categories entity和类别实体
@Data
@AllArgsConstructor
@Entity
@Table(name="categories")
public class Categories {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long categoryId;
@NotBlank(message = "Please Add Category name ")
@Length(max =100 ,min =2)
private String categoryName ;
@Length(max=500,min=2)
private String categoryDescription;
@EqualsAndHashCode.Exclude
@ToString.Exclude
@ManyToMany(mappedBy = "categories", fetch = FetchType.EAGER)
private Set<User> users = new HashSet<>();
}
and I have this table where user and categories are mapped.我有这张表,其中映射了用户和类别。
mysql> select * from users_categories where category_id=5;
+---------+-------------+
| user_id | category_id |
+---------+-------------+
| 3 | 5 |
| 7 | 5 |
+---------+-------------+
2 rows in set (0.00 sec)
I want to retrieve all userId with a specific category.我想检索具有特定类别的所有 userId。 How do we achieve this in spring boot and JPA?我们如何在 spring 启动和 JPA 中实现这一点? Here is my user repository这是我的用户存储库
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long>{
Optional<User> findByUsername(String username);
}
I didn't test it but try to add this to your UserRepository
:我没有对其进行测试,但尝试将其添加到您的UserRepository
:
@Query("select u from User u inner join u.categories c where c.categoryId =:id")
List<User> findByCategory(@Param("id") Long id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.