hibernate复合主键的解决方法

背景:做毕设时遇到了一个问题,因为需要而创建了一个无主键的表,在java中使用@Entity注释该类时编译不通过,仔细查看,是因为没有主键通不过的。

过程结果:后来通过查资料,使用了一种解决方法,现在予以记录,方便以后回来查看。先附上成功后的代码(将每个字段的get,set方法省略):

public class call_namepk implements Serializable {

    private static final long serialVersionUID = 1L;

    //weekNumber,studentid,courseid将被用来做复合主键
    private int weekNumber;

    private int studentid;

    private int courseid;

    public call_namepk() {
    }

    //说是要有带有参数的构造方法
    public call_namepk(int weekNumber, int studentid, int courseid) {
        this.weekNumber = weekNumber;
        this.studentid = studentid;
        this.courseid = courseid;
    }

    //说是一定要覆盖@Override equals()与hashCode,我没做过修改但好像没发现问题
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        call_namepk that = (call_namepk) o;
        return weekNumber == that.weekNumber &&
                studentid == that.studentid &&
                courseid == that.courseid;
    }

    @Override
    public int hashCode() {

        return Objects.hash(weekNumber, studentid, courseid);
    }

    //每个字段的get(), set()方法已被省略。
}

@Entity
@IdClass(call_namepk.class)
public class call_name{

    @Id
    private int weekNumber;

    @Id
    private int studentid;

    @Id
    private int courseid;


    //每个字段的get(), set()方法已被省略。
}

现在还不太懂这里面的过程原理,mark –2018-03-11

你可能感兴趣的:(hibernate)