Home > Enterprise >  spring JPA query to find events by locationId and categoryId
spring JPA query to find events by locationId and categoryId

Time:11-30

This is my events entity.

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


}

In my controller ,i have access to locationId and categoryId as request params . I am not getting how to define my eventsRepository to access by locationId and categoryId. What changes should i make to this repo for things to work .

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

CodePudding user response:

I think a few adjustments you need to get rid of the issue. The query builder uses actual column names, so if your column name is locationId, then use 'findByLocationId(Integer locationId)' as a prototype. And please make sure entity names suit table names.

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

This is off-topic, but I would like to mention that please do not use Lombok in entity classes. Getter, setter, and construction generators are ok, but hascode and string generators would be dangerous if you use lazy initialization. You may not get benefits from lazy loadings.

CodePudding user response:

You have 2 ways to get your jpa-query working:

  1. Modify your JPA-Query:

    @Repository

public interface EventsRepository extends JpaRepository<Events,Long> 
{
    public Events findByCateories_IdAndLocation_id(Long categoriesId, long locationId)
}
  1. Use a custom query - annotate your jpa with @Query and use a native query

There is one additional point from my side. Naming of your classes. You are using plural which conflicts with the business logic - especially to the DB-relations(see Events to Categories). I would use singular (Event, Category)

  • Related