Multiple Entities Mapped to the Same Table

ID

java.hibernate_multiple_entities_per_table

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

hibernate, orm, reliability

Description

Reports when two or more @Entity classes within the same compilation unit are mapped to the same physical table via @Table(name="…​") or by defaulting to the class name. This is usually a modelling error that causes concurrency problems and cache inconsistencies.

Rationale

When multiple entity classes map to the same database table, Hibernate maintains separate persistence contexts for each. Changes made through one entity are invisible to the other, leading to stale data, lost updates, and second-level cache corruption.

// Bad: two entities mapped to the same table
@Entity @Table(name = "users")
class UserEntity { @Id Long id; }

@Entity @Table(name = "users")
class UserView { @Id Long id; }

Remediation

Use a single @Entity class per table. For read-only projections, use DTO projections, @Subselect, or database views instead of mapping a second entity to the same table.

// Good: single entity per table
@Entity @Table(name = "users")
class UserEntity { @Id Long id; }

// For read-only access, use a DTO projection
interface UserProjection {
    Long getId();
    String getName();
}