ManyToOne mapping

It is also possible to back reference from the ContactDetails entity to the Person entity using the @ManyToOne annotation:

@Table(name = "contacts")
@Entity
class ContactDetails {
@Id
private lateinit var id: Integer
lateinit var number: String

@Enumerated(EnumType.STRING)
private var type: ContactType? = null

@ManyToOne(cascade = arrayOf(CascadeType.ALL), fetch =
FetchType.LAZY)
lateinit var person: Person
}

In the preceding code snippets, we have illustrated an example of the OneToMany and ManyToOne annotations. Similarly, we can use the OneToOne and ManyToMany annotations.

A relationship between two classes can be one of the following:

  • Bidirectional: Both classes hold a reference to the other
  • Unidirectional: Only one class stores the reference of the other

Let's now move on to talk about binding Address to a Person entity. Address is not an entity; it is just a model object. If it were an entity, we could specify the relationship as we did for the ContactDetails entity, binding Address and Person. Instead, we will use the @Embedded annotation:

@Table(name = "person")
@Entity
class Person : Identity() {
@Id
lateinit var identifier: UUID
lateinit var name: PersonName
lateinit var loginId: String

@Enumerated(EnumType.STRING)
var preferredLanguage: PreferredLanguage? = null

    @OneToMany(cascade = arrayOf(CascadeType.ALL), fetch = 
FetchType.LAZY)
@JoinColumn(name = "PERSON_ID", nullable = false)
lateinit var contact: List<ContactDetails>
@Embedded
lateinit var address: Address
}

We need to mark the Address class with the @Embeddable annotation, which is shown in the following code:

@Embeddable
class Address {
lateinit var street: String
lateinit var city: String
lateinit var state: String
lateinit var country: String
}

This means that no separate table is created for Address as it is not an entity. All the properties of Address will be inserted into the person table.

All the fields defined in the class are mapped to the columns of a table in the database. To make JPA not persist a field, we can annotate it with the @Transient annotation.

For example, consider the following code:

@Table(name = "person")
@Entity
data class Person(val loginId: String) : Identity() {
@Id
lateinit var identifier: UUID

@Transient
late init var lastName: String

@Enumerated(EnumType.STRING)
var preferredLanguage: PreferredLanguage? = null

@Embedded
lateinit var address: Address
}

In this case, the lastName field is not mapped to a column in a person table.

In this section, we have discussed how to use the @Entity annotation for the entities of our domain. We specified the @Embedded annotation for model-type objects and we established the mapping between the entities and the data classes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset