【问题标题】:JPA - Changing the Name of the mappedBy columnJPA - 更改 mappedBy 列的名称
【发布时间】:2015-08-16 14:10:35
【问题描述】:

好的,我有一个将学期映射到他们的课程的应用程序;

public class Course {

    private String courseId;
    private String courseName;

    private Collection<Semester> semesters = new ArrayList<>();

    @OneToMany(targetEntity = Semester.class, mappedBy = "course")
    public Collection<Semester> getSemesters() {
        return semesters;
    }

    public void setSemesters(Collection<Semester> semesters) {
        this.semesters = semesters;
    }

    @Id
    @Column (name = "COURSE_ID")
    public String getCourseId() {
        return courseId;
    }

    public void setCourseId(String courseId) {
        this.courseId = courseId;
    }

    @Column(name = "COURSE_NAME", nullable = false, unique = true)
    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
}

如您所见,用户类使用一对多映射映射到学期实体。

学期课程如下;

@Entity
@Table (name = "SEMESTERS")
public class Semester {

    private int semNum;
    private Course course;

    @ManyToOne
    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

    @Id
    @Column (name = "SEM_NUM")
    public int getSemNum() {
        return semNum;
    }

    public void setSemNum(int semNum) {
        this.semNum = semNum;
    }
}

如您所见,我使用mappedBy 将课程直接映射到学期表中。但问题是学期表中的字段为course_COURSE_ID

如何将此列名称更改为 COURSE_ID

【问题讨论】:

    标签: java jpa hibernate-onetomany


    【解决方案1】:

    你需要使用@JoinColumn注解。

    @ManyToOne
    @JoinColumn(name="COURSE_ID")
    public Course getCourse() { 
       //code
    }
    

    我建议您阅读documentation,因为那里对此进行了很好的解释。如果您不想阅读文档,那么请准备好漫长而痛苦的旅程,因为 JPA 不是一项简单的技术,它有很多陷阱。

    【讨论】:

    • 您指的是哪个 JPA 文档?我在网上找到了多个 Hibernate Docs。我不知道该跟随哪个。我很困惑。
    • 我在我的答案中链接了文档:)。而且您对 hibernate 的不同文档集是正确的,请始终确保您使用的是您正在使用的版本中的文档,因为配置已更改。
    【解决方案2】:

    您可以在学期课程中通过@JoinColumn 更改此设置。这允许更改默认的 JPA 名称。 应该是这样的:

    public class Semester {
    
        @ManyToOne
        @JoinColumn(name="COURSE_ID")
        public Course getCourse() {
            return course;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 2017-01-23
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多