user184794
user184794

Reputation: 1036

ManyToOne relation in Hibernate, not in Database

I have an entity named 'Department' and another entity named 'student'. I know the department will have many students and there shoulld be relation between these two tables in database. But in my project, the DB tables are already there and there is no relation (foreign key) between department and student tables.

In entity class, student.java , there is a relation written as,

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = 'DeptId', nullable = false, insertable = false, updatable = false)
Department department

I am confused about this existing code.

When I wrote a test, I am fetching the department from DB by deptId and set the student entity as,

student.setDepartment(department);

This doesn't populate the DB column 'DEPTID' in student table.

Since there's no student collection in Department, I cannot set the student as,

department.addStudents(student);

I am not sure whether we can insist a @ManyToOne relation without a relation between the tables in DB.

Please let me know how I can fix this issue so that the 'DEPTID' column in student table is populated with the correct data.

Thanks in advance, BS

Upvotes: 1

Views: 1310

Answers (2)

Ephesian Lukong
Ephesian Lukong

Reputation: 1

Hi sorry for responding to your question so late but I think the reply could equally help another person. Now you said the tables existed already in the database, if they haven't yet got some data then I suggest you drop them, activate your Table Generation Strategy in your persistence.xml file to Create, in that case, it will recreate those tables with your desired relationship columns. Do not also forget to use the @OneToMany annotation on the Department.java class to indicate its capabilities of reception of many students. It is used together with the @ManyToOne

Upvotes: 0

Subin Sebastian
Subin Sebastian

Reputation: 10997

you r having

@JoinColumn(name = 'DeptId', nullable = false, insertable = false, updatable = false) instead why dont you try

@JoinColumn(name = 'DeptId', nullable = false)

Hibernate wont check whether the mapping constraints that you are putting are valid at db level. It just assumes it is valid and executes queries based on that assumption.

Upvotes: 1

Related Questions