无法添加或更新子行:外键约束失败

时间:2016-05-13 13:30:34

标签: jpa foreign-keys many-to-many integrity

我正在尝试与JPA实现多对多的关系。我有3张桌子:

Korisnik(用户):id,username列。 Tim(团队):d,name,desc columns。 Korisnik_Tim :korisnik_id,tim_id。

以下是我的实体类:

Korisnik课程:

public class Korisnik implements Serializable, AbstractModelObject {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Lob
@Size(min = 1, max = 65535)
@Column(name = "username")
private String username;
@ManyToMany(mappedBy = "korisnikCollection", cascade = CascadeType.ALL)
private Collection<Tim> timCollection;

// Getters and setters

这是 Tim 类:

public class Tim implements Serializable, AbstractModelObject {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Lob
@Size(min = 1, max = 65535)
@Column(name = "name")
private String name;
@Lob
@Size(max = 65535)
@Column(name = "opis")
private String opis;
  @JoinTable(name = "tim_korisnik", joinColumns = {
    @JoinColumn(name = "korisnik_id", referencedColumnName = "id")}, inverseJoinColumns = {
    @JoinColumn(name = "tim_id", referencedColumnName = "id")})
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
 private Collection<Korisnik> korisnikCollection;

在前端,我正在尝试添加团队,并为该团队添加一些用户。

 public void save(){
    tim = new Tim();
    tim.setName(name);
    tim.setOpis(desc);
    tim.setKorisnikCollection(selectUsers);
    databaseBroker.save(tim);

 }

这里我试图将数据保存到db。

@Override
public void save(AbstractModelObject amo) {
    try{
        em.merge(amo);
    } catch (Exception e){
        System.err.println(e.getLocalizedMessage());
    }     
}

这是expcetion:

Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`nst`.`tim_korisnik`, CONSTRAINT `fk_korisnik` FOREIGN KEY (`korisnik_id`) REFERENCES `korisnik` (`id`) ON UPDATE CASCADE)
Error Code: 1452
Call: INSERT INTO tim_korisnik (tim_id, korisnik_id) VALUES (?, ?)
bind => [2 parameters bound]
Query: DataModifyQuery(name="korisnikCollection" sql="INSERT INTO tim_korisnik (tim_id, korisnik_id) VALUES (?, ?)")

更新: 我也尝试了这个,但没效果。

 public void save(){
    tim = new Tim();
    tim.setName(name);
    tim.setOpis(desc);
    for(int i=0;i<selectUsers.size();i++){
        selectUsers.get(i).setTimCollection(Arrays.asList(tim));
    }
    tim.setKorisnikCollection(usersList);
    databaseBroker.save(tim);

}

1 个答案:

答案 0 :(得分:0)

ManyToMany关联是双向的。开发者的可重复性是维持协会双方的连贯性。

您确定所有用户都在&#34; selectUsers&#34;有他们的&#34; tim&#34;设置为当前时间?

Morover我不会设置该集合,但我更喜欢将所有用户添加到tim集合中。

尽管有CASCADE.ALL属性,我还是会在提交事务之前尝试保留所有用户。