简体   繁体   中英

Jpa part of composite key mapping

I have the following table:

@Entity(name = 'STUDENT')
class Student {
   @Id    
   @Column(name = 'STUDENT_ID')
   String studentId

   @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "id.student")
   Set<Disabilities> disabilities = [] 
}


@Entity(name = 'STUDENT_DISABILITY')
class Disability {

    @EmbeddedId
    DisabilityId id

    @Nullable
    @Column(name = 'MOD_DT')
    LocalDateTime modifiedDate
}

@Embeddable
class DisabilityId implements Serializable {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = 'STUDENT_ID')
    Student student

    @Column(name = 'DISABILITY_CD')
    String disabilityCode
}

This all works fine but I am trying to join a new table 'Disability_info' table to 'Disability' table. This is the Disability_info table:

@Entity
@Table(name = 'DISABILITY_INFO')
class DisabilityInfo {

    @Id
    @Column(name = 'DISABILITY_CD')
    String id

    @Column(name = 'DISABILITY_NAME')
    String disabilityName

    @Column(name = 'DISABILITY_DESC')
    String disabilityDesc
}

The problem that I am having is that the DisabilityInfo's primary key is part of the composite key of the Disability class. All I want is the below with sql:

SELECT * FROM DISABILITY a INNER JOIN DISABILITY_INFO b on a.DISABILITY_CD = b.DISABILITY_CD

Can anybody please shed some light to how I can achieve that ?

Thank you in advance.

I figured it out. A many to one association was required. My initial thought was that one disability should have one description therefore there is a 1 : 1 relationship.

However, in reality, there are multiple disabilities that references the same description which means this is in fact a many to one relationship!

@Entity(name = 'STUDENT_DISABILITY')
class Disability {

@EmbeddedId
DisabilityId id

@Nullable
@Column(name = 'MOD_DT')
LocalDateTime modifiedDate


@ManyToOne
@JoinColumn(name = 'DISABILITY_ID, insertable = false, updatable = false)
DisabilityInfo disabilityInfo

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM