Skip to content
Advertisement

JPA integrity constraint violated – parent key not found when trying to save entity with JoinColumn

I am trying to save a User Entity with Roles under it. It seems like since the roles do not have their user id foreign key set it fails to save, is there a way to tell jpa to set the role’s user id after it saves the user but before it saves the user’s roles? Or will I need to remove the cascade save, save the User, set the role user ids, and then save the roles manually?

import lombok.*;

import javax.persistence.*;
import java.sql.Timestamp;
import java.util.List;

@Entity
@Table(name = "USER")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long userId;

    @JoinColumn(name = "userId", referencedColumnName = "userId")
    @OneToMany(cascade=CascadeType.ALL)
    private List<UserRoles> userRoles;

}

and roles:

import lombok.*;

import javax.persistence.*;

@Entity
@Table(name = "USER_ROLES")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class UserRoles {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long userRolesId;

    @Column
    private long userId;

    @Column
    private long roleId;

}

Error from calling UserRepository.save(user) when roles are present:

oracle.jdbc.OracleDatabaseException: ORA-02291: integrity constraint (APP_OWNER.SYS_C009043) violated - parent key not found

The SYS_C009043 constraint is a foreign key constraint in the USER_ROLES table requiring userId to exist in the USER table

Advertisement

Answer

Try the following mapping instead:

@Entity
@Table(name = "USER")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long userId;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<UserRoles> userRoles;

}

@Entity
@Table(name = "USER_ROLES")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class UserRoles {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long userRolesId;

    @ManyToOne(fetch = LAZY)
    @JoinColumn(name = "userId")
    private User user;

    @Column
    private long roleId;

}
Advertisement