Search code examples
javasqldatabasejpahibernate-mapping

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


I am trying to add information into 2 tables with one to one annotation. enter image description here

enter image description here

As you can see votes_id and voter_sinNumber doesn't insert foreign keys. here is my dao.java methods

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();    
    }

And this is how I declare Voter and votes:

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;
    }


}

It throws an error:

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))


Solution

  • You need to cascade changes:

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