当前位置: 代码迷 >> java >> 一对一注释不会将外键插入表中
  详细解决方案

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

热度:49   发布时间:2023-07-25 19:20:01.0

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

正如您所看到的,vote_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;


}

选民.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 ,约束FKdyr88aepaxedeiivxepemku28外键( voter_sinNumber )参考votersinnumber ))

您需要级联更改:

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

// On Votes side
@OneToOne(cascade=CascadeType.ALL)
private Voter voter;
  相关解决方案