codergirrl
codergirrl

Reputation: 155

How to declare two foreign keys as primary keys in an entity

I have two table which are student and course in my spring code. I want to create a relationship table, "takeCourse". I will have only student id and course id. I can create a table with two primary keys in my java code but I can not declare them as foreign key.

I tried this solution Two foreign keys as primary key but it didn't work out I think there is some missing parts in there. So I tried this based on this solution:

(Student entity has id, name, surname) (Course entity has id, coursename)

// This is embedded id:
@Embeddable
public class CompositeKey implements Serializable {
    public long getSid() {
        return sid;
    }

    public void setSid(long sid) {
        this.sid = sid;
    }

    public long getCid() {
        return cid;
    }

    public void setCid(long cid) {
        this.cid = cid;
    }

    @Column(name="sid")
    private long sid;

    @Column(name="cid")
    private long cid;
}

//This is takeCourse entity code
@Entity
@Table(name="takeCourse")
public class takeCourse implements Serializable {
    @EmbeddedId CompositeKey id;


    @ManyToMany
    @JoinColumn(name = "sid")
    public Student getStudent(StudentRepository repo){
        return repo.findById(id.getSid());
    }

    @ManyToMany
    @JoinColumn(name = "cid")
    public Course getStudent(CourseRepository repo){
        return repo.findById(id.getCid());
    }

}

I expected to create table with two fk as pk. but the result is:

create table take_course (cid int8 not null, sid int8 not null, primary key (cid, sid))

there is no foreign key info.

I want it to be create table take_course (cid int8 not null, sid int8 not null, primary key (cid, sid), forign key sid references student (id), foreigr key cid references course (id))

Is there anybody can see where did I go wrong?

Upvotes: 0

Views: 604

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36103

I try to answer your question.

TakeCourse (Classes in Java start with an upper letter) is the relation between Course and Student.

So your entity should look like this:

@Entity
@Table(name="takeCourse")
public class TakeCourse implements Serializable {


    @EmbeddedId 
    private CompositeKey id;

    @MapsId    
    @ManyToOne
    @JoinColumn(name = "sid")
    private Student student;

    @MapsId        
    @ManyToOne
    @JoinColumn(name = "cid")
    private Course course;

    // getters and setters
}

Please find the documentation about MapsId here:

https://docs.oracle.com/javaee/7/api/javax/persistence/MapsId.html

https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#identifiers-derived

Upvotes: 1

Related Questions