¿Por qué estoy recibiendo un error cuando estoy tratando de insertar un nuevo objeto en db?

dragos.pavel:

Mi escenario es el siguiente

Un usuario puede tener una lista de Track , correspondiente a ella, el Track entidad contiene un ID de usuario. ( @OneToMany)

Siempre que se crea una nueva pista, se actualizará la lista de pistas.

entidades antes mencionadas son las siguientes:

pista Entidad

@Entity
@Table(name ="track")
public class Track {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long trackId;

@ManyToOne
@JoinColumn(name = "userId", nullable = false)
private User user;

@OneToOne(mappedBy = "track")
private Share share;

private String trackName;

@OneToMany(mappedBy = "pointId")
private List<Point> point;

@OneToOne(mappedBy = "track")
private TrackStatistic trackStatistic;

usuario Entidad

@Entity
@Table(name = "user")
public class User {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "USER_ID")
private Long id;

private String firstName;

private String lastName;

@Column(unique = true)
private String username;

private String password;

@Column(unique = true)
private String email;

@Column(unique = true)
private String phoneNumber;

private int age;

private Role role;

@OneToMany(mappedBy = "shareId")
private List<Share> shares;

@OneToMany(mappedBy = "trackId")
private List<Track> tracks;

}

createTrack método es como sigue

public Track createTrack(String username, TrackDTO trackDTO) {
    //Find user
    User user = userRepository.findByUsername(username);

    //Convert Dto to Entity
    Track track = modelMapper.map(trackDTO, Track.class);

    //Update user track list
    user.getTracks().add(track);

    //Update track
    track.setUser(user);

    //save user
    userRepository.save(user);

    //save track
    return trackRepository.save(track);
}

Tenga en cuenta que TrackDTOes una clase de entidad correspondiente Dto Pista


Cuando me encontré createTrack, me enfrenté al siguiente error:

2020-01-18 20:48:23.315 ERROR 14392 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper:
 Cannot add or update a child row: a foreign key constraint fails (`thdb`.`track`, CONSTRAINT `FK5cftk3hw8vfnaigtj063skvxs` FOREIGN KEY (`track_id`) REFERENCES `user` (`user_id`))

2020-01-18 20:48:23.338 ERROR 14392 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]:
 Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails 
(`thdb`.`track`, CONSTRAINT `FK5cftk3hw8vfnaigtj063skvxs` FOREIGN KEY (`track_id`) REFERENCES `user` (`user_id`))
dragos.pavel:

Refactorizado la relación entre las entidades y el problema aún persisten. Como un pequeño adelanto de la relación entre la vía y el usuario se parece a continuación: entidad Track

@Entity
@Table(name ="TRACK")
public class Track {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "TRACK_ID")
    private Long trackId;

    private String trackName;

    @OneToMany(cascade = CascadeType.ALL,
            orphanRemoval = true)
    @JoinColumn(name = "POINT_ID")
    private List<Point> point;

    @OneToOne
    @JoinColumn(name="TRACK_STATISTIC_ID")
    private TrackStatistic trackStatistic;

    private long numberOfLikes;

    private Date creationTime;

entidad de usuario

@Entity
@Table(name = "USER")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "USER_ID")
    private Long userId;

    private String firstName;

    private String lastName;

    @Column(unique = true)
    private String username;

    private String password;

    @Column(unique = true)
    private String email;

    @Column(unique = true)
    private String phoneNumber;

    private int age;

    private Role role;

    private boolean locked;

    private long numberOfReports;

    @JsonIgnore
    @ManyToMany()
    @JoinTable(name="FOLLOWER",
            joinColumns={@JoinColumn(name="USER_ID")},
            inverseJoinColumns={@JoinColumn(name="FOLLOWER_ID")})
    private Set<User> followed = new HashSet<User>();

    @JsonIgnore
    @ManyToMany(mappedBy="followed")
    private Set<User> follower = new HashSet<User>();

   //How it was before
    @OneToMany
    @JoinColumn(name = "TRACK_ID")
    private List<Track> tracks;

   //How is it now
    @OneToMany
    @JoinColumn(name = "USER_ID")
    private List<Track> tracks;


    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "SHARE_ID")
    private List<Share> shares;

y el método que se llama cuando se crea una pista es:

public Track createTrack(String username, TrackDTO trackDTO) {
        Track track = modelMapper.map(trackDTO, Track.class);
        Track newTrack = trackRepository.save(track);
        return newTrack;
    }

Así que el problema estaba en la anotación @JoinColumn en la lista de pistas, puse el nombre TRACK_ID en lugar de USER_ID

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=362728&siteId=1
Recomendado
Clasificación