2

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')

3
  • Could you add the code where you are using the result of findAll ? Commented Nov 13, 2018 at 13:20
  • I added service class, where findAll() method called @Arnaud Commented Nov 13, 2018 at 13:33
  • 1
    JPA has no such "findAll". That is "Spring Data JPA", different API Commented Nov 13, 2018 at 14:07

2 Answers 2

9

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 } 
Sign up to request clarification or add additional context in comments.

2 Comments

I get some rows of null using this method. Any idea?
Another way of defining composite primary key: public class Event { @EmbeddedId private IdClassName id; private String description; // getter and setter code } @Embeddable public class IdClassName implements Serializable { private String name; private Date eventDateTime; // getter and setter code }
2

Your name-column is the identifier of the entity (@Id), yet your sample-data contains the String data two times.

Identifiers have to be unique, if you manually assign them (i.e. not using generated identifier) it's the appliations responsibility to keep them unique.

If not strange behaviour may occur.

So you should either fix your sample data or use another column (with generated values) as the identifier of the entitiy.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.