Junior — Middle
What characteristics should a class have to be used correctly as an entity in Hibernate?
sobes.tech AI
Answer from AI
To correctly use a class as an entity in Hibernate, it must:
- Have a unique identifier (usually a field annotated with
@Id). - Be serializable (implement
Serializable— not always necessary, but recommended). - Have a public or protected no-argument constructor.
- Use getters and setters for fields (Hibernate works through properties).
- Not contain complex logic in the constructor.
Example:
@Entity
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
public User() {} // mandatory 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; }
}