【问题标题】:spring JPA query to find events by locationId and categoryIdspring JPA查询通过locationId和categoryId查找事件
【发布时间】:2022-01-06 15:03:02
【问题描述】:

这是我的事件实体。

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Events {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long eventId;


    @NotBlank(message = "Please Add Event name ")
    @Length(max =100 ,min =2)
    private String eventName ;



    private String eventDescription;

    // Each event is going to be mapped to a Location
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(
            name = "location_id",
            referencedColumnName = "locationId"
    )
    @NotNull
    private Location location ;


    @Temporal(TemporalType.DATE)
    Date eventStartDate;

    @Temporal(TemporalType.DATE)
    Date eventEndDate;




    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(
            name = "category_id",
            referencedColumnName = "categoryId"
    )
    @NotNull
    private Categories categories;


}

在我的控制器中,我可以访问 locationId 和 categoryId 作为请求参数。 我不知道如何定义我的 eventsRepository 以通过 locationId 和 categoryId 访问。我应该对此 repo 进行哪些更改才能正常工作。

@Repository
public interface EventsRepository extends JpaRepository<Events,Long> {
    public Events findByCateoryAndLocation()
}

【问题讨论】:

  • findByCategoryIdAndLocationId(long id, long id)。类似的东西取决于CategoryLocation@Id 字段的名称。

标签: spring spring-boot spring-data-jpa


【解决方案1】:

这正是我在本机查询的帮助下为解决这个问题所做的。

@Query(
            value = "SELECT * FROM events  where category_id = ?1 AND location_id = ?2",
            nativeQuery = true
    )
    public List<Events> findByCategoryIdAndLocationIdIn(Long CategoryId , Long LocationId);

【讨论】:

    【解决方案2】:

    您有两种方法可以让您的 jpa 查询正常工作:

    1. 修改您的 JPA 查询:

      @Repository

    public interface EventsRepository extends JpaRepository<Events,Long> 
    {
        public Events findByCateories_IdAndLocation_id(Long categoriesId, long locationId)
    }
    
    1. 使用自定义查询 - 使用 @Query 注释您的 jpa 并使用本机查询

    我这边还有一点。 你的类的命名。您正在使用与业务逻辑冲突的复数 - 特别是与数据库关系(请参阅事件到类别)。我会使用单数(事件,类别)

    【讨论】:

      【解决方案3】:

      我认为您需要进行一些调整才能解决此问题。查询生成器使用实际的列名,因此如果您的列名是 locationId,则使用“findByLocationId(Integer locationId)”作为原型。请确保实体名称适合表名称。

      @Repository
      public interface EventRepository extends JpaRepository<Event, Integer>
      {
          Event findByLocationIdAndCategoryId(Integer locationId, Integer categoryId);
      }
      

      这是题外话,但我想提一下,请不要在实体类中使用 Lombok。 Getter、setter 和构造生成器都可以,但是如果使用延迟初始化,hascode 和字符串生成器会很危险。您可能无法从延迟加载中获益。

      【讨论】:

        猜你喜欢
        • 2015-02-21
        • 2018-02-20
        • 1970-01-01
        • 2020-01-25
        • 2015-08-04
        • 2022-01-24
        • 1970-01-01
        • 2017-08-18
        相关资源
        最近更新 更多