I have the following tables in Db2.
CREATE TABLE DB2ADMIN.School (school_id SMALLINT PRIMARY KEY NOT NULL, name varchar(128));
create table DB2ADMIN.Student (student_id int PRIMARY KEY NOT null, name varchar(128) not null, age smallint not null, school_id int NOT NULL, FOREIGN KEY (school_id) REFERENCES School(school_id));
I can successfully insert records into the tables using the Db2 console.
INSERT INTO db2admin.school VALUES (1, 'BJS');
INSERT INTO db2admin.STUDENT VALUES (1, 'Pankaj', 30, 1);
One School can contain many students. Here is how I am defining the entity relationships in Hibernate 5.4.18.
@Entity
@Table(name = "school")
public class School
{
@Id
@SequenceGenerator(name = "SchoolIdSequence", schema="db2admin", sequenceName = "Sequence_School", allocationSize = 1)
@GeneratedValue(generator = "SchoolIdSequence", strategy = GenerationType.SEQUENCE)
@Column(name = "SCHOOL_ID")
private int id;
@Column(name = "NAME")
private String name;
@OneToMany(fetch = FetchType.LAZY, cascade=CascadeType.ALL, mappedBy = "school")
//@JoinColumn(name="student_id", nullable=false)
private Set<Student> students;
public School()
{}
public School(String name)
{
this.name = name;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Set getStudents()
{
return students;
}
public void setStudents(Set students)
{
this.students = students;
}
@Override
public String toString()
{
return "School [Name = '" + name + "']";
}
}
@Entity
@Table(name = "student")
public class Student
{
@Id
@SequenceGenerator(name = "SequenceStudentId", sequenceName = "Sequence_Student", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SequenceStudentId")
@Column(name = "STUDENT_ID")
private int id;
@Column(name = "NAME")
private String name;
@Column(name = "AGE")
private int age;
@ManyToOne(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name="school_id", nullable=false)
private School school;
public Student()
{}
public Student(String name, int age, School school)
{
this.name = name;
this.age = age;
this.school = school;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
@Override
public String toString()
{
return "Student [id=" + id + ", Name=" + name + ", Age=" + age + "]";
}
}
I get the following error on executing the application.
org.hibernate.AnnotationException: @OneToOne or @ManyToOne on org.jfa.persistence.hibernate.entity.Student.school references an unknown entity: org.jfa.persistence.hibernate.entity.School
I have tried to tweak the relationship settings in the class in different ways as suggested by others on Internet/StackOverFlow. Yet, no luck so far. Please help.