Entity class
public class Event {
@Id
private String name;
private String description;
private Date eventDateTime;
//getter and setter code
}
Service Class
EventService {
@Autowired EventRepository eventRepository;
List<Event> getEvents () {
List<Event> events = eventRepository.findAll();
return events;
}
}
For sample data set: Event ('add', '', '2018-01-01 00:00:10') Event ('add', '', '2018-01-01 00:10:10') Event ('delete', '', '2018-01-01 00:20:00') Event ('edit', '', '2018-01-01 00:30:00')
JPA findAll() query return repeated rows:
Event ('add', '', '2018-01-01 00:00:10') Event ('add', '', '2018-01-01 00:00:10') Event ('add', '', '2018-01-01 00:00:10') Event ('add', '', '2018-01-01 00:00:10')
To avoid repeated (duplicate) data, we have to ensure there is a unique key and that will be annotated by @Id. In this example, name it self is not unique, that's why the result show duplicate data. eventDateTime is better choice as unique field.
public class Event {
private String name;
private String description;
@Id
private Date eventDateTime;
//getter and setter code
}
Or, we can define a composite unique key with name and eventDateTime.
public class CompositeKey implements Serializable {
private String name;
private Date eventDateTime;
}
Then, annotated Event class with @IdClass(CopositeKey.class) and both name and eventDateTime field with @Id
@IdClass(CopositeKey.class)
public class Event {
@Id
private String name;
private String description;
@Id
private Date eventDateTime;
//getter and setter code
}