Sobes.tech
Junior

Can the Entity class be abstract?

sobes.tech AI

Answer from AI

Yes, it can. The abstract class Entity can serve as a base class for other entities, providing common properties or methods that should be inherited. This helps avoid code duplication and implement polymorphism. The JPA specification allows the use of abstract classes as parent classes for entities through inheritance strategies (@Inheritance).

Example:

// Abstract base class Entity
@Entity
@Inheritance(strategy = InheritanceType.JOINED) // Example inheritance strategy
public abstract class BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // Common properties or methods
    public Long getId() {
        return id;
    }

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

Child class Entity:

// Child class inheriting from abstract BaseEntity
@Entity
public class ConcreteEntity extends BaseEntity {

    private String name;

    // Properties specific to ConcreteEntity
    public String getName() {
        return name;
    }

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