gpt4 book ai didi

java - 一对一注释不会将外键插入表中

转载 作者:行者123 更新时间:2023-12-02 10:11:41 25 4
gpt4 key购买 nike

我正在尝试将信息添加到带有一对一注释的 2 个表中。 enter image description here

enter image description here

正如您所看到的 votes_id 和 voter_sinNumber 没有插入外键。这是我的 dao.java 方法

public void addVoter(Voter voter) { 
Session session = sessionFactory.openSession();
session.beginTransaction();

session.save(voter);

session.getTransaction().commit();
session.close();
}


public void addVote(Votes votes) {
Session session = sessionFactory.openSession();
session.beginTransaction();


Voter voter = new Voter();
voter.setVotes(votes);
votes.setVoter(voter);

session.save(votes);

session.getTransaction().commit();
session.close();
}

这就是我宣布选民和投票的方式:

投票.java:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Votes implements Serializable{

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private int id;

private String party;

public Votes(String party) {
this.party = party;
}

@OneToOne
private Voter voter;


}

Voter.java:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@NamedQuery(name="Voter.byName", query="from Voter where sinNumber=:sinNumber")
public class Voter implements Serializable{
@Id
private int sinNumber;

private String fname;
private String lname;
private int year;
private int month;
private int day;

private String address;


@OneToOne
private Votes votes;


public Voter(int sinNumber, String fname, String lname,
int year, int month, int day, String address) {
this.sinNumber = sinNumber;
this.fname = fname;
this.lname = lname;
this.year = year;
this.month = month;
this.day = day;
this.address = address;
}


public Voter(String fname, String lname, int year, int month, int day,
String address, Votes votes) {
this.fname = fname;
this.lname = lname;
this.year = year;
this.month = month;
this.day = day;
this.address = address;
this.votes = votes;
}


}

它抛出一个错误:

java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (hibernatedb.votes, CONSTRAINT FKdyr88aepaxedeiivxepemku28 FOREIGN KEY (voter_sinNumber) REFERENCES voter (sinnumber))

最佳答案

您需要级联更改:

// On Voter side
@OneToOne(cascade=CascadeType.ALL)
private Votes votes;

// On Votes side
@OneToOne(cascade=CascadeType.ALL)
private Voter voter;

关于java - 一对一注释不会将外键插入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54963276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com