在Custom bridge table in playframework ebean中有一个例子,说明如何使用@EmbeddedId在Java中使用Ebean映射模型。但Scala语言没有这样的例子。
假设我们在Scala中有以下3级模型:
学生班:
class Student (aId: Int, fName: String, lName: String) {
val id:Int=aId
val firstName:String=fName
val lastName:String=lName
var enrollments:java.util.List[Enrollment]
}
课程类:
class Course (aId: Int, aName: String) {
val id:Int=aId
val name:String=aName
var enrollments:java.util.List[Enrollment]
}
报名课程:
class Enrollment (aDesc: String, aStudent: Student, aCourse: Course) {
val description:String=aDesc
val enrollmentId:EnrollmentId
val student:Student = aStudent
val course:Course = aCourse
}
如何在PlayFramework中使用Ebean将此模型映射到数据库?
答案 0 :(得分:0)
这可以通过以下方式完成:
学生班:
@Entity
class Student (aId: Int, fName: String, lName: String) {
@Id
val id:Int=aId
@Column(name="first_name")
val firstName:String=fName
@Column(name="last_name")
val lastName:String=lName
@OneToMany(mappedBy="student")
var enrollments:java.util.List[Enrollment] = _
}
课程类:
@Entity
class Course (aId: Int, aName: String) {
@Id
val id:Int=aId
@Column(name="name")
val name:String=aName
@OneToMany(mappedBy="course")
var enrollments:java.util.List[Enrollment] = _
}
报名课程:
@Entity
class Enrollment (aDesc: String, aStudent: Student, aCourse: Course) {
@Column(name="name")
val description:String=aDesc
@EmbeddedId
val enrollmentId:EnrollmentId = new EnrollmentId(aStudent.id, aCourse.id)
@ManyToOne
@JoinColumn(name = "student_id", insertable = false, updatable = false)
val student:Student = aStudent
@ManyToOne
@JoinColumn(name="course_id", insertable = false, updatable = false)
val course:Course = aCourse
}
EnrollmentId类:
@Embeddable
class EnrollmentId (aStudentId: Int, aCourseId: Int) {
val student_id:Int = aStudentId
val course_id:Int = aCourseId
override def hashCode(): Int = student_id + course_id
override def equals(that: Any): Boolean = {
that match {
case e: EnrollmentId => this.student_id == e.student_id && this.course_id == e.course_id
case _ => false
}
}
}
此代码中最重要的是从Enrollment到Student的关系以两种方式映射:
但是这种关系只能通过复合键保存。 @ManyToOne关系具有@JoinColumn属性'可插入'和'可更新的'设置为false,这就是为什么不以这种方式保存它。