Sobes.tech
Junior — Middle

What requirements are imposed on a class for proper work with Hibernate?

sobes.tech AI

Answer from AI

For proper operation with Hibernate, an entity class must meet the following requirements:

  • Have a public no-argument constructor (default constructor).
  • The class should be a plain old Java object (POJO) — it should not be final, so Hibernate can create proxies.
  • Fields mapped to table columns are usually private with public getters and setters.
  • The class must have a unique identifier (a field annotated with @Id).
  • It is recommended to correctly implement the equals() and hashCode() methods based on the identifier.

Example:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    public User() {} // mandatory default constructor

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;
        User user = (User) o;
        return id != null && id.equals(user.getId());
    }

    @Override
    public int hashCode() {
        return 31;
    }
}