英文:
In @OneToMany making One's side owner
问题
假设有一个名为 Employee
的类,其中有一个关联集合 Course
。
class Employee {
@OneToMany
private Set<Course> courses;
}
我想要类似下面的结果:
first_name | last_name | course_ids
Jill | Smith. | 1,2,3
Eve | Jackson. | 1,4,5
我在 Hibernate 方面了解不是很深,可以有人帮忙吗?
英文:
Let's say there is an Employee
's which has a collection of Course
.
class Employee {
@OneToMany
private Set<Course> courses.
}
I want something like below
first_name | last_name | course_ids
Jill | Smith. | 1,2,3
Eve | Jackson. | 1,4,5
I am not so advanced in hibernate, can someone please help.
答案1
得分: 0
以下是翻译好的内容:
我即将向您展示的方法是一对多单向方法。在您的数据库中,您应该为课程创建一张表,其中必须包含employee_id作为外键和课程id作为主键。然后,按照以下方式创建Course类(假设数据库中的课程表名为“course”):
@Entity
@Table(name = "course")
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name ='id')
private int id;
//您可以根据课程表添加其他字段
//添加一个无参数的构造函数,以及getter和setter方法
}
请注意,employee_id 不在 Course 类中。然后创建 Employee 类:
@Entity
@Table(name ="employee")
public class Employee {
//ID 和其他字段
@OneToMany
@JoinColumn(name="course_id")
private List<Course> courses;
//构造函数、getter 和 setter 方法等
}
您必须在您创建的每个实体中定义 getter 和 setter 方法,因为 Hibernate 使用它们将从数据库检索到的值设置到实体的字段中。
英文:
The method that I am about to show to you is the One to many unidirectional method.
In your database you should create a table for courses and it must contain employee_id as a foreign key and an id of the course as a primary key.
Then, create the Course class as below.(let's assume that the name of the course table in the database is "course":
@Entity
@Table(name = "course")
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name ='id')
private int id;
//You can add another fields based on your course table
//add a constructor with no arguments, getters and setters
}
Notice that the employee_id is not in the course class.Then create the employee class:
@Entity
@Table(name ="employee")
public class Employee {
//ID and other fields
@OneToMany
@JoinColumn(name="course_id")
private List<Course> courses;
//Constructor,getters and setters,...
}
You must define getters and setters in every Entity you create because Hibernate uses them to set the fields in the Entity with the value retrieved from the database
专注分享java语言的经验与见解,让所有开发者获益!
评论