Nested exception is javax.persistence.EntityNotFoundException

Viewed 12437

I'm using spring boot and and spring data in my project and i have two classes:

class Mission implements Serializable { private static final long 
serialVersionUID = 1L;
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long              id;
private String            departure;
private String            arrival;
private Boolean           isFreeWayEnabled;
@OneToMany( mappedBy = "mission" )
private List<Station>     stations;
// getters and setters
}

and the second class is :

@Entity
public class Station implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long              id;
private String            station;

@ManyToOne( fetch = FetchType.LAZY )
@JsonBackReference
private Mission           mission;
//getters and setters
 }

Methode which add Mission:

public Mission addMision( Mission mission ) {
// TODO Auto-generated method stub
// Mission mission = getMissionById( mission.getId() );
for ( Station station : mission.getStations() ) {
    station.setMission( mission );
    stationRepository.save( station );
}
return missionRepository.save( mission );
}

when i tried to add a new Mission it gives this error :

"Unable to find com.carpooling.entity.Station with id 2; nested exception is javax.persistence.EntityNotFoundException: Unable to find com.carpooling.entity.Station with id 2"

heres the JSON object Sent:

{"departure":"fff","arrival":"ffff","isFreeWayEnabled":false,"stations":[{"id":1},{"id":2}]}

2 Answers

If you do things right...

In my case the error was due to trying to use @ElementCollection annotation for a map of non-@Embeddable objects (actually, a `Map<Integer, @Entity>.

My solution went through mapping objects in a flatter way to make them likeable by JPA. The detail was getting rid of the parent entity that acted as aggregator and saving by hand the different collections that it was holding (three repositories instead of one, three save() invocations instead of one, one less table).

Related