hibernate-find entities,在集合中有另一个实体

fkaflof6  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(255)

我有两个类:evententity和interestentity。evententity有一组有趣的属性。我的问题是,如何只找到内部具有给定兴趣的事件实体。如何在eventrepository类中实现它?
我的evententity类:

@Entity
@Table(name = "EVENTS")
public class EventEntity {

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

    private String name;

    @ManyToMany(mappedBy = "events")
    private Set<InterestEntity> interests;

    // Getters and Setters
}

我的兴趣班:

@Entity
@Table(name = "INTERESTS")
public class InterestEntity {

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

    private String name;

    @ManyToMany
    @JoinTable(name = "events_interests",
                joinColumns = {@JoinColumn(name = "interest_id")},
                inverseJoinColumns = {@JoinColumn(name = "event_id")})
    private Set<EventEntity> events;

    // Getters and Setters
}

我试过这样的方法,但没用:

public interface EventRepository extends JpaRepository<EventEntity, Long> {

    List<EventEntity> findByInterestsContains(InterestEntity interestEntity);
}
rkue9o1l

rkue9o1l1#

jparepository不会“理解”findbyinterestscontains方法,因此您需要创建自己的eventrepository接口实现。为了使用jpa查询方法,您需要检查文档规则https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-方法.查询-创建

lf3rwulv

lf3rwulv2#

public interface EventRepository extends JpaRepository<EventEntity, Long> {

    @Query("select e from EventEntity e join e.interests i where i.id=:id group by e")
    List<EventEntity> findByInterestsId(Long id);
}
4xrmg8kj

4xrmg8kj3#

如果你想找到感兴趣的id,你可以随意选择

public interface EventRepository extends JpaRepository<EventEntity, Long> {

    List<EventEntity> findByInterestsIdIn(List<Long> ids);
}

如果你看的是特定的id,那么它会像

public interface EventRepository extends JpaRepository<EventEntity, Long> {

    List<EventEntity> findByInterestsId(Long id);
}

相关问题