1

For my project I'm using Fullcalendar and Spring. The event data from my sql db is divided in these columns: id - doctor_id - patient_id - start - end.

I want to display only event associated to the logged user (data necessaries for login are contained in another sql table named Doctor): now is displaying event of all the users.

This is my controller class:

@RestController
class EventController {
    
    @Autowired
    private EventJpaRepository eventRepository;
    
    @RequestMapping(value="/allevents", method=RequestMethod.GET)
    public List<Event> events() {
        return eventRepository.findAll();
    }
    
    @RequestMapping(value="/events", method=RequestMethod.GET)
    public List<Event> getEventsInRange(@RequestParam(value = "start", required = true) String start, 
                        @RequestParam(value = "end", required = true) String end, @RequestParam(value = "title", required = true) String title) {
    Date startDate = null;
    Date endDate = null;
    SimpleDateFormat inputDateFormat=new SimpleDateFormat("yyyy-MM-dd");

    try {
        startDate = inputDateFormat.parse(start);
    } catch (ParseException e) {
        throw new BadDateFormatException("bad start date: " + start);
    }

    try {
        endDate = inputDateFormat.parse(end);
    } catch (ParseException e) {
        throw new BadDateFormatException("bad end date: " + end);
    }

    LocalDateTime startDateTime = LocalDateTime.ofInstant(startDate.toInstant(),
    ZoneId.systemDefault());

    LocalDateTime endDateTime = LocalDateTime.ofInstant(endDate.toInstant(),
    ZoneId.systemDefault());

    return eventRepository.findByDateBetween(startDateTime, endDateTime); 
    }
}

This is the event repository:

@Repository
interface EventJpaRepository extends JpaRepository<Event, Long> {
        
    @Query("select b from Event b where b.start >= ?1 and b.end <= ?2")
    public List<Event> findByDateBetween(LocalDateTime start, LocalDateTime end);
    
}

And this is the fullcalendar script inside my html page:

<script> 
    document.addEventListener('DOMContentLoaded', function() {
        var calendarEl = document.getElementById('calendar');
        var calendar = new FullCalendar.Calendar(calendarEl, {
            initialView : 'dayGridMonth',
            headerToolbar: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek,timeGridDay'
            },
            locale: 'it',
            editable : false,
            eventLimit : true, // allow "more" link when too many events
            events : {
                url : '/allevents',
                type : 'GET',
                error : function() {
                    alert('there was an error while fetching events!');
                },
            }
        });     
        calendar.render();
    });

    
</script>
Radix
  • 254
  • 1
  • 8

1 Answers1

2

There are a couple things your code is missing. Right now, your query returns all events within a time range. To restrict that to just the logged in user, you will need to join the Doctor table in the query with the user's id. Not knowing how your session is being stored, or what your Doctor table looks like, your query probably needs to be updated something like:

@Query("select b from Event b join Doctor d on b.doctor_id=d.id where b.doctorId = ?1 AND b.start >= ?2 and b.end <= ?3")
public List<Event> findByDoctorIdAndDateBetween(Long doctorId, LocalDateTime start, LocalDateTime end, String userId);

I haven't tested that, but that should get you going in the correct direction.

EDIT: Sorry, it has been a while since I have written JPA. I have updated the above query, and you will need a

@OneToMany(mappedBy="doctorId")
List<Event> events;

On the Doctor object. And a

@ManyToOne
Long doctorId

On the Event. Then you should be able to pass in the doctor_id to the query after retrieving it from your session. This question Joining two table entities in Spring Data JPA gives some good info on how to join tables in JPA queries.

Niro
  • 776
  • 8
  • 15
  • Thanks! I'd tried but I get an error: Error creating bean with name 'eventController': Unsatisfied dependency expressed through field 'eventRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'eventJpaRepository' defined in com.labprogettazione.prenotazionemedica.EventJpaRepository. I think that findbydatebetween needs to have only localdatetime interval. – Radix Apr 07 '21 at 18:39
  • Doesn't work. It gives me error: ManyToOne … references an unknown entity. I tried changing doctorid in event to: @ManyToOne(targetEntity=Doctor.class) @JoinColumn(name="doctorid", referencedColumnName = "id") private Long doctorid; but it gives me this error: Can not set java.lang.Long field com.labprogettazione.prenotazionemedica.Event.doctorid to com.labprogettazione.prenotazionemedica.Doctor – Radix Apr 07 '21 at 19:54