繁体   English   中英

Hibernate 外键必须与多对多上引用的主键具有相同的列数

[英]Hibernate Foreign key must have same number of columns as the referenced primary key on many-to-many

我正在尝试使用 JPA 实现给定的数据库结构在此处输入图像描述

SQL 脚本:

DROP TABLE IF EXISTS StudentLesson;
DROP TABLE IF EXISTS StudentCourse;
DROP TABLE IF EXISTS Lesson;
DROP TABLE IF EXISTS Course;
DROP TABLE IF EXISTS Student;

CREATE TABLE IF NOT EXISTS Course
(
    courseId    BIGINT       NOT NULL AUTO_INCREMENT,
    name        VARCHAR(150) NOT NULL,
    description TEXT         NULL,
    actual      TINYINT      NOT NULL DEFAULT 1,
    PRIMARY KEY (courseId)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS Lesson
(
    lessonId    BIGINT       NOT NULL AUTO_INCREMENT,
    courseId    BIGINT       NOT NULL,
    name        VARCHAR(150) NOT NULL,
    orderNumber INTEGER      NULL,
    actual      TINYINT      NOT NULL DEFAULT 1,
    PRIMARY KEY (lessonId),
    CONSTRAINT FK__Lesson__courseId FOREIGN KEY Lesson (courseId) REFERENCES Course (courseId)

CREATE TABLE IF NOT EXISTS Student
(
    studentId BIGINT NOT NULL AUTO_INCREMENT,
    userId    BIGINT NOT NULL,
    PRIMARY KEY (studentId),
    CONSTRAINT FK__Student__userId FOREIGN KEY Student (userId) REFERENCES User (userId)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS StudentCourse
(
    studentCourseId  BIGINT        NOT NULL AUTO_INCREMENT,
    studentId        BIGINT        NOT NULL,
    courseId         BIGINT        NOT NULL,
    percentCompleted DECIMAL(5, 2) NOT NULL DEFAULT 0.0,
    PRIMARY KEY (studentCourseId),
    CONSTRAINT FK__StudentCourse__studentId FOREIGN KEY StudentCourse (studentId) REFERENCES Student (studentId),
    CONSTRAINT FK__StudentCourse__courseId FOREIGN KEY StudentCourse (courseId) REFERENCES Course (courseId)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS StudentLesson
(
    studentLessonId  BIGINT        NOT NULL AUTO_INCREMENT,
    studentCourseId  BIGINT        NOT NULL,
    lessonId         BIGINT        NOT NULL,
    percentCompleted DECIMAL(5, 2) NOT NULL DEFAULT 0.0,
    PRIMARY KEY (studentLessonId),
    CONSTRAINT FK__StudentLesson__studentCourseId FOREIGN KEY StudentLesson (studentCourseId) REFERENCES StudentCourse (studentCourseId),
    CONSTRAINT FK__StudentLesson__lessonId FOREIGN KEY StudentLesson (lessonId) REFERENCES Lesson (lessonId)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_unicode_ci;

这是我的实体类:学生

@Entity
@Table(name = "Student")
@Getter
@Setter
public class StudentDBO extends AbstractDBO {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "studentId", nullable = false)
    private Long studentId;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "userId", nullable = false)
    private UserDBO user;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name="StudentCourse",
            joinColumns={@JoinColumn(name="studentId")},
            inverseJoinColumns={@JoinColumn(name="courseId")})
    private Set<CourseDBO> courses;

}

课程

@Entity
@Table(name = "Course")
@Getter
@Setter
public class CourseDBO extends AbstractDBO {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "courseId", nullable = false)
    private Long courseId;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "description")
    private String description;

    @Column(name = "actual")
    private Boolean actual;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "course", cascade = CascadeType.ALL)
    private Set<LessonDBO> lessons;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy="courses")
    private Set<StudentDBO> students;

}

@Entity
@Table(name = "Lesson")
@Getter
@Setter
public class LessonDBO extends AbstractOrderedDBO {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "lessonId", nullable = false)
    private Long lessonId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "courseId", nullable = false)
    private CourseDBO course;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "actual")
    private Boolean actual;

}

学生课程

@Entity
@Table(name = "StudentCourse")
@Getter
@Setter
public class StudentCourseDBO extends AbstractDBO {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "studentCourseId", nullable = false)
    private Long studentCourseId;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "studentId", nullable = false)
    private StudentDBO student;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "courseId", nullable = false)
    private CourseDBO course;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "studentCourse")
    private Set<StudentLessonDBO> studentLessons;

    @Column(name = "percentCompleted", nullable = false)
    private BigDecimal percentCompleted;

}

学生课

@Entity
@Table(name = "StudentLesson")
@Getter
@Setter
public class StudentLessonDBO extends AbstractDBO {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "studentLessonId", nullable = false)
    private Long studentLessonId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "studentCourseId", nullable = false)
    private StudentCourseDBO studentCourse;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "lessonId", nullable = false)
    private LessonDBO lesson;

    @Column(name = "percentCompleted", nullable = false)
    private BigDecimal percentCompleted;

}

当我尝试启动我的应用程序时,它给了我错误Foreign key (FKr8cmxbjotnbr91mtv62sakwva:StudentLesson [studentCourseId])) must have same number of columns as the referenced primary key (StudentCourse [studentId,courseId])完整堆栈跟踪:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is org.hibernate.MappingException: Foreign key (FKr8cmxbjotnbr91mtv62sakwva:StudentLesson [studentCourseId])) must have same number of columns as the referenced primary key (StudentCourse [studentId,courseId])
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1788) ~[spring-beans-5.3.1.jar:5.3.1]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:609) ~[spring-beans-5.3.1.jar:5.3.1]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.1.jar:5.3.1]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.1.jar:5.3.1]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.1.jar:5.3.1]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.1.jar:5.3.1]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.1.jar:5.3.1]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:330) ~[spring-beans-5.3.1.jar:5.3.1]
    ... 28 common frames omitted
Caused by: org.hibernate.MappingException: Foreign key (FKr8cmxbjotnbr91mtv62sakwva:StudentLesson [studentCourseId])) must have same number of columns as the referenced primary key (StudentCourse [studentId,courseId])
    at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:148) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:130) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.secondPassCompileForeignKeys(InFlightMetadataCollectorImpl.java:1929) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.secondPassCompileForeignKeys(InFlightMetadataCollectorImpl.java:1845) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1665) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:286) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1224) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1255) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.1.jar:5.3.1]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.1.jar:5.3.1]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.1.jar:5.3.1]
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

可能是什么问题? 我使用多对多关系表 StudentCourse 错了吗? 错误说,StudentLesson 必须有多个列引用,但在数据库中 StudentCourse 有单个主键列 (studentCourseId),而不是 (studentId, courseId)。

AbstractDBO的外观如何? 也许你也在那里声明一个 id ?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM