I am working with Eclipselink and having issue with using secondary table. I have two tables as below.
Student with columns student_id(Primary Key), student_name etc.
Registration with columns student_id(FK relationship with Student table), course_name (with not null constraint) etc.
The requirement is student may or may not have registration. If student has registration, the data should be persisted to Registration table as well. Otherwise only Student table should be persisted.
My code snippet is as below.
Student.java
------------
@Entity
@Table(name = "STUDENT")
@SecondaryTable(name = "REGISTRATION")
@Id
@Column(name = "STUDENT_ID")
private long studentId;
@Basic(optional=true)
@Column(name = "COURSE_NAME", table = "REGISTRATION")
private String courseName;
I tried the following scenarios. 1. Student with registration - Working fine. Data is added to both Student and Registration tables 2. Student without registration - Getting error such as 'COURSE_NAME' cannot be null.
Is there a way to prevent persisting into secondary table?
Any help is much appreciated.
Thanks!!!
As @Eelke states, the best solution is to define two classes and a OneToOne relationship.
Potentially you could also use inheritance, having a Student and a RegisteredStudent that adds the additional table. But the relationship is a much better design.