Session 5 - Hibernate - Advanced Mappings
Session 5 - Hibernate - Advanced Mappings
ADVANCED MAPPINGS
HIBERNATE – Advanced Mappings
• One-to-One Mapping:
Shared Primary Key
– In a one-to-one association, you can use a
shared primary key, where the primary key of
the associated entity is the same as the
primary key of the main entity.
– This can be achieved using
@PrimaryKeyJoinColumn or @JoinColumn
annotations.
• One-to-Many and Many-to-One Mapping:
Bidirectional Association:
– In a bidirectional one-to-many/many-to-one
relationship, you can use the @OneToMany
and @ManyToOne annotations to establish
the association between two entities.
– Make sure to use mappedBy attribute in
@OneToMany to indicate the reverse side of
the association.
• Many-to-Many Mapping:
Bidirectional Association:
– In a many-to-many relationship, you can
use the @ManyToMany annotation to
associate two entities.
– Similar to one-to-many, you should use
the mappedBy attribute in
@ManyToMany to specify the reverse side
of the association.
• Embedded Objects:
}
Passport entity class:
import javax.persistence.*;
@Entity
@Table(name = "passports")
public class Passport {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "passport_id")
private Long id;
@Column(name = "number")
private String number;
@OneToOne
@JoinColumn(name = "person_id")
private Person person;
// Constructors, getters, setters, and other properties
// ...
}
Annotations and Configurations:
@Entity
@Table(name = "authors")
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "author_id")
private Long id;
@Column(name = "name")
private String name;
@Embedded
private Address address;
}
Address embedded object class:
import javax.persistence.Embeddable;
@Embeddable
public class Address {
}
Book entity class:
import javax.persistence.*;
@Entity
@Table(name = "books")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "book_id")
private Long id;
@Column(name = "title")
private String title;
@ManyToOne
@JoinColumn(name = "author_id")
private Author author;
// Constructors, getters, setters, and other properties
// ...
}
Annotations and Configurations
authors table.
• With these mappings, Hibernate will
handle the relationships between the
Author and Book entities and persist
them into the corresponding database
tables accordingly.