-1

In Custom bridge table in playframework ebean there is an example how to map model using @EmbeddedId with Ebean in Java. But there is no such example for Scala language.

Lets assume we have a following 3-class model in Scala:

Student class:

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]
} 

Course class:

class Course (aId: Int, aName: String) { 

    val id:Int=aId
    val name:String=aName
    var enrollments:java.util.List[Enrollment]
}

Enrollment class:

class Enrollment (aDesc: String, aStudent: Student, aCourse: Course) { 

    val description:String=aDesc
    val enrollmentId:EnrollmentId
    val student:Student = aStudent
    val course:Course = aCourse
}

How to map this model to database using Ebean in PlayFramework?

Community
  • 1
  • 1
rtruszk
  • 3,902
  • 13
  • 36
  • 53

1 Answers1

0

This can be done in following way:

Student class:

@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] = _
}

Course class:

@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] = _
}

Enrollment class:

@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 class:

@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
        }
    }
}

The most important thing in this code is that relations from Enrollment to Student is mapped in two ways:

  • as @ManyToone relation
  • as column of composite key

But this relation is saved only through composite key. @ManyToOne relation has @JoinColumn attributes 'insertable' and 'updateable' set to false and this is why it is not saved this way.

rtruszk
  • 3,902
  • 13
  • 36
  • 53