Implementing Object-Relational Mapping

1. Implementing Entity Mappings

Example: JPA entity

@Entity
@Table(name = "orders")
public class Order {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullable = false) private String status;
    @Column(name = "placed_at", nullable = false) private Instant placedAt;
}

2. Implementing Relationships

RelationshipAnnotation
1:1@OneToOne
1:N@OneToMany (mappedBy on owning side)
N:1@ManyToOne (owns FK)
M:N@ManyToMany + @JoinTable

3. Implementing Fetch Strategies

TypeDefaultRecommendation
@ManyToOneEAGERSet LAZY explicitly
@OneToOneEAGERLAZY
@OneToManyLAZYKeep LAZY
@ManyToManyLAZYKeep LAZY
Note: Use JPQL JOIN FETCH or entity graphs to avoid N+1 selects.

4. Implementing Cascade Operations

CascadeEffect
PERSISTSave children with parent
MERGEUpdate children
REMOVEDelete children with parent
DETACH/REFRESHPropagate to children
ALLEverything
orphanRemoval=trueDelete orphaned children

5. Implementing Inheritance Strategies

StrategyTablesTrade-off
SINGLE_TABLEOne per hierarchyFast; sparse columns
JOINEDOne per class + joinNormalized; slower reads
TABLE_PER_CLASSOne per concrete classNo FK from base

6. Implementing Embedded Objects

Example: Embeddable value object

@Embeddable
public class Address {
    private String street; private String city; private String zip;
}

@Entity
public class Customer {
    @Embedded
    @AttributeOverride(name="city", column=@Column(name="billing_city"))
    private Address billing;
}

7. Implementing Entity Listeners

CallbackTrigger
@PrePersistBefore insert
@PostPersistAfter insert
@PreUpdateBefore update
@PostUpdateAfter update
@PreRemove/@PostRemoveDelete
@PostLoadAfter fetch

8. Implementing Named Queries

Example: Named JPQL

@NamedQuery(name = "Order.findOpen",
    query = "select o from Order o where o.status = 'OPEN'")
@Entity
public class Order { ... }

em.createNamedQuery("Order.findOpen", Order.class).getResultList();

9. Implementing Custom Type Converters

Example: AttributeConverter

@Converter(autoApply = true)
public class MoneyConverter implements AttributeConverter<Money, Long> {
    public Long convertToDatabaseColumn(Money m) { return m == null ? null : m.cents(); }
    public Money convertToEntityAttribute(Long c) { return c == null ? null : Money.usd(c); }
}

10. Implementing ID Generation Strategies

StrategyTrade-off
IDENTITYSimple; defeats batch insert
SEQUENCEBest for batch; PG/Oracle
TABLEPortable; slower
UUIDDistributed-friendly
Application-assignedDomain controls; ULID/UUIDv7

11. Implementing Composite Primary Keys

Example: @EmbeddedId

@Embeddable
public record OrderLineId(Long orderId, int lineNo) implements Serializable {}

@Entity
public class OrderLine {
    @EmbeddedId private OrderLineId id;
}

12. Implementing Optimistic Locking

Example: @Version

@Entity
public class Account {
    @Id private Long id;
    @Version private Long version;  // auto-incremented; throws OptimisticLockException on stale write
    private long balanceCents;
}