一对一注释不会将外键插入 table

one to one annotation doesn't insert foreign key into a table

我正在尝试将信息添加到具有一对一注释的 2 个表中。

如您所见,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();    
    }

这就是我声明选民和投票的方式:

Votes.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;