Sobes.tech
Senior

What types of relationships in Hibernate do you know and how to describe them? What entity states exist?

sobes.tech AI

Answer from AI

In Hibernate, the following types of relationships between entities exist:

  1. One-to-One — one entity is related to one other entity.

    @OneToOne
    @JoinColumn(name = "passport_id")
    private Passport passport;
    
  2. One-to-Many — one entity is related to many others.

    @OneToMany(mappedBy = "owner")
    private List<Car> cars;
    
  3. Many-to-One — many entities are related to one.

    @ManyToOne
    @JoinColumn(name = "owner_id")
    private Owner owner;
    
  4. Many-to-Many — many entities are related to many others.

    @ManyToMany
    @JoinTable(
        name = "student_course",
        joinColumns = @JoinColumn(name = "student_id"),
        inverseJoinColumns = @JoinColumn(name = "course_id")
    )
    private Set<Course> courses;
    

Entity states in Hibernate:

  • Transient — object is created but not associated with a session and not saved in the database.
  • Persistent — object is associated with a session and tracked by Hibernate; changes will be synchronized with the database.
  • Detached — object was associated with a session, but the session is closed; the object is not tracked.
  • Removed — object is marked for deletion from the database upon the next commit.

Understanding these states is important for proper management of object lifecycle and efficient database operations.