一对一注释不会在表中插入外键

时间:2019-03-02 21:38:57

标签: java hibernate jpa

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

enter image description here

如您所见,voice_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:无法添加或更新子行:外键约束失败(hibernatedbvotes,CONSTRAINT FKdyr88aepaxedeiivxepemku28外键(voter_sinNumber)参考文献votersinnumber

1 个答案:

答案 0 :(得分:1)

您需要级联更改:

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

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