0

Okay I have an application that maps Semesters to their courses;

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

As you can see the users class is mapped to the Semesters entity using One to Many mapping.

The Semester class is as follows;

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

As you can see I am using mappedBy to map the course directly into the semester table. But the problem is that the field in the semester table comes as course_COURSE_ID.

How can I change this column name to just COURSE_ID ?

buræquete
  • 14,226
  • 4
  • 44
  • 89
Kramer786
  • 1,238
  • 1
  • 12
  • 26

2 Answers2

3

You need to use the @JoinColumn annotation.

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

I would suggest you to read the documentation as this is very well explained in there. If you don't want to read the docs, then be ready for a long and painful journey, as JPA is not a simple technology, and it has a multitude of gotchas.

Augusto
  • 28,839
  • 5
  • 58
  • 88
  • Which JPA doc do you refer ? I have found multiple Hibernate Docs online. I don't know which to follow. I am confused. – Kramer786 Aug 16 '15 at 16:24
  • I linked the docs in my answer :). And you're correct about the different documentation sets from hibernate, always make sure you're using the docs from the version you're using as the config has changed. – Augusto Aug 16 '15 at 16:28
1

You can change this via @JoinColumn in the Semester class. This allow to change the default JPA names. Should look like this:

public class Semester {

    @ManyToOne
    @JoinColumn(name="COURSE_ID")
    public Course getCourse() {
        return course;
    }
}
buræquete
  • 14,226
  • 4
  • 44
  • 89
mszalbach
  • 10,612
  • 1
  • 41
  • 53