Practice: entities and mapping
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
A new table arrives and you must map it correctly the first time. Most mapping bugs repeat the same few mistakes, and each has a clear error message you can learn to read.
From CREATE TABLE to entity, column by column
Mapping a table means turning each line of its CREATE TABLE into one field, in a fixed order. Example 1 maps ShopLite's order_items, whose order_id and product_id stay plain Integer columns until the Relationships module.
- Table name →
@Entityand@Table(name = "..."). - Primary key →
@Id,@GeneratedValue(strategy = GenerationType.IDENTITY),@Column(name = "..._id"),IntegerforINT. - Each column → a field whose type matches:
VARCHAR/CHAR→String(or a converted value type),INT→intorInteger,DECIMAL→BigDecimal,DATETIME→LocalDateTime,DATE→LocalDate,BOOLEAN→boolean. - Names that are not the snake case of the field, and
NOT NULL, lengths and uniqueness →@Column(...). - Enums →
@Enumerated(EnumType.STRING); value groups →@Embeddable; database-filled or audited columns →insertable/updatableor auditing. - Protected no-arg constructor, getters, business methods, id-based
equals, constanthashCode, shorttoString.
Example 1 · Mapping order_items: OrderItem.java and a check run
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
/*The table (Section 12 schema)CREATE TABLE order_items ( order_item_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, order_id INT NOT NULL, product_id INT NOT NULL, quantity INT NOT NULL, unit_price DECIMAL(10,2) NOT NULL, ... );*/
// src/main/java/com/shoplite/order/OrderItem.javapackage com.shoplite.order;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.Table;
import java.math.BigDecimal;
@Entity@Table(name = "order_items")public class OrderItem {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "order_item_id") private Integer id;
@Column(name = "order_id", nullable = false) private Integer orderId;
@Column(name = "product_id", nullable = false) private Integer productId;
@Column(nullable = false) private int quantity;
@Column(name = "unit_price", nullable = false, precision = 10, scale = 2) private BigDecimal unitPrice;
protected OrderItem() { }
public OrderItem(Integer orderId, Integer productId, int quantity, BigDecimal unitPrice) { this.orderId = orderId; this.productId = productId; this.quantity = quantity; this.unitPrice = unitPrice; }
public Integer getId() { return id; } public Integer getOrderId() { return orderId; } public Integer getProductId() { return productId; } public int getQuantity() { return quantity; } public BigDecimal getUnitPrice() { return unitPrice; }
public BigDecimal lineTotal() { return unitPrice.multiply(BigDecimal.valueOf(quantity)); }
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof OrderItem other)) return false; return id != null && id.equals(other.getId()); }
@Override public int hashCode() { return OrderItem.class.hashCode(); }
@Override public String toString() { return "OrderItem[id=" + id + ", productId=" + productId + ", quantity=" + quantity + "]"; }}
// src/main/java/com/shoplite/order/OrderItemDemoRunner.javapackage com.shoplite.order;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
import java.math.BigDecimal;import java.util.List;
@Componentclass OrderItemDemoRunner implements CommandLineRunner {
private final OrderItemRepository items;
OrderItemDemoRunner(OrderItemRepository items) { this.items = items; }
@Override public void run(String... args) { // order_items rows 24 and 25 are the two lines of order 14 BigDecimal total = BigDecimal.ZERO; for (OrderItem item : items.findAllById(List.of(24, 25))) { System.out.println(item + " x " + item.getUnitPrice() + " = " + item.lineTotal()); total = total.add(item.lineTotal()); } System.out.println("Order 14 total: " + total); }}DEBUG ... org.hibernate.SQL : select oi1_0.order_item_id,oi1_0.order_id,oi1_0.product_id,oi1_0.quantity,oi1_0.unit_price from order_items oi1_0 where oi1_0.order_item_id in (?,?) OrderItem[id=24, productId=1, quantity=1] x 17999.00 = 17999.00 OrderItem[id=25, productId=6, quantity=1] x 1299.00 = 1299.00 Order 14 total: 19298.00
What this code does
- Every column became one field by the routine:
order_item_idneeded@Column(name),unit_priceisBigDecimalwithprecision = 10, scale = 2,quantityis a primitiveintbecause it isNOT NULL. - The app started, so validation agreed with the table.
findAllByIdloaded both lines of order 14 in oneSELECT ... in (?,?). - The total 19298.00 matches order 14 in the API contract: the unit price stored on the order line, never the product's current price.
Fixing mappings from schema-validation errors
Schema validation reports one problem per start. Fix the field it names, start again, and repeat. Example 2 fixes a broken Order entity in three starts.
Example 2 · A broken Order entity, fixed in three starts
Runs in: the mapping-lab practice project (Spring Boot 4.1, Hibernate 7, the ShopLite MySQL database)
@Entity@Table(name = "orders") // "order" is an SQL keyword, so the table is "orders"public class Order {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "order_id") private Long id;
@Column(name = "customer_id", nullable = false) private Integer customerId; // plain columns until the Relationships module
@Column(name = "address_id", nullable = false) private Integer addressId;
@Column(nullable = false, length = 10) private OrderStatus status;
@Column(nullable = false) private LocalDateTime placedAt; // constructor, getters ...}Start 1: Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: wrong column type encountered in column [order_id] in table [orders]; found [int (Types#INTEGER)], but expecting [bigint (Types#BIGINT)] Fix: Long id -> Integer id (and JpaRepository<Order, Integer>). Start 2: Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: missing column [placed_at] in table [orders] Fix: @Column(name = "ordered_at", nullable = false). Start 3: Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: wrong column type encountered in column [status] in table [orders]; found [varchar (Types#VARCHAR)], but expecting [tinyint (Types#TINYINT)] Fix: @Enumerated(EnumType.STRING) on status. Start 4: Order 14: SHIPPED at 2026-09-21T21:05 Order 14 can be delivered next
What this code does
- Three different mistakes, three starts: validation stops at the first problem it finds, so a clean start is the only proof that all are fixed.
- Each message named the table and column.
foundwas always the database's type, so every fix was on the Java side. - Start 4 is the runner from the Enums lesson: the fixed entity reads order 14 correctly.
Read the last Caused by: line, then match it to one of three shapes:
missing table [x]: the@Tablename is missing or wrong.missing column [x] in table [t]: a field name became a column that does not exist, so fix the field or add@Column(name = ...).wrong column type ... found [A], but expecting [B]:Ais the database,Bcomes from your Java type; change the Java type (LongtoInteger,doubletoBigDecimal, add@Enumerated(EnumType.STRING)).
Errors that validation cannot see (wrong lengths, missing NOT NULL, a record entity, a bad hashCode) need a code review, which the practice tasks train.
Choosing: STRING or ORDINAL, BigDecimal or double, embeddable or entity
Four choices come up on every table, each with one safe default. Example 3 shows what the wrong choices do to data.
Example 3 · Three wrong choices and what they do to data
import java.math.BigDecimal;import java.time.Instant;import java.time.LocalDateTime;import java.time.ZoneId;import java.time.ZoneOffset;
enum ModeV1 { UPI, CARD, COD }
enum ModeV2 { UPI, NETBANKING, CARD, COD } // a new mode added in the middle
public class MappingChoicesDemo {
public static void main(String[] args) { // 1. Enums: what a stored value means after the enum changes int storedOrdinal = ModeV1.COD.ordinal(); String storedName = ModeV1.COD.name(); System.out.println("ORDINAL " + storedOrdinal + " now reads " + ModeV2.values()[storedOrdinal] + "; STRING '" + storedName + "' now reads " + ModeV2.valueOf(storedName));
// 2. Money: a fee of Rs 0.10 per UPI payment, 30 payments double asDouble = 0; BigDecimal asDecimal = BigDecimal.ZERO; for (int i = 0; i < 30; i++) { asDouble += 0.10; asDecimal = asDecimal.add(new BigDecimal("0.10")); } System.out.println("double: " + asDouble + ", BigDecimal: " + asDecimal);
LocalDateTime stored = LocalDateTime.of(2026, 9, 21, 21, 5); Instant readAsUtc = stored.toInstant(ZoneOffset.UTC); System.out.println("LocalDateTime: " + stored + ", Instant shown in India: " + readAsUtc.atZone(ZoneId.of("Asia/Kolkata")).toLocalDateTime()); }}ORDINAL 2 now reads CARD; STRING 'COD' now reads COD double: 3.0000000000000013, BigDecimal: 3.00 LocalDateTime: 2026-09-21T21:05, Instant shown in India: 2026-09-22T02:35
What this code does
- A plain-Java model of three mapping choices. A cash-on-delivery payment stored as ordinal 2 turns into a card payment once
NETBANKINGis added; stored as a name it staysCOD. - Thirty fees of Rs 0.10 drift with
doubleand stay exactly3.00withBigDecimal. - Order 14's India time
21:05, read as a UTCInstant(what Hibernate 7 does on MySQL), shows as 02:35 the next day in India. None of the three raises an error.
The defaults, each with a reason you should be able to say aloud:
- Enums: always
EnumType.STRING.ORDINALstores positions, which change meaning when constants are added or reordered, without any error. - Money: always
BigDecimalon aDECIMAL(p,2)column.doublecannot hold most decimal fractions exactly, so totals drift by paise. - Embeddable vs entity: does anything refer to it by id, or does it have a life of its own? Then it is an entity with a table. Does it only describe its owner, compared by its values? Then embed it.
- Dates:
LocalDateTimefor wall-clockDATETIMEcolumns (ShopLite: India time);Instantonly for columns that hold UTC.
Interview drill: entity rules, equals/hashCode and auditing
Interviewers often ask these three topics together, as "walk me through your entity class". Answer in this order, each in one or two sentences, and name a real error you have seen.
Entity rules: @Entity with @Id, a protected no-arg constructor because Hibernate creates the objects, not final because of proxies; a record cannot be an entity. equals/hashCode: id-based equals that is true only for equal non-null ids, a constant hashCode so it never changes after save(), instanceof and getters because of proxies. Auditing: @CreatedDate and @LastModifiedDate filled by Spring Data's listener after @EnableJpaAuditing, with a fixed-zone clock.
The interview tab has the full answers; say them out loud until each takes under a minute.
Finish up
Mark complete & continue
Next: ShopLite: map products, customers, addresses and orders