✅ Short Answer
You need custom type conversion when you want to map Java types that don’t directly match database column types, or when you need to store complex or non-standard values — beyond what JPA handles automatically.
🔎 Detailed Explanation
🔹 Common scenarios where you need custom conversion:
✅ Value objects in your domain:
- Example:
Money
,Distance
,GeoCoordinate
,Percentage
. - These usually wrap multiple fields or add behavior → but in the DB, you need to store them as one or more columns.
✅ Enums with custom representations:
- E.g., storing enum codes like “A”, “B” instead of enum ordinal or name.
- Mapping between a business-friendly enum and a legacy DB value.
✅ Non-standard or vendor-specific DB types:
- PostgreSQL
jsonb
,hstore
,inet
. - Oracle
SDO_GEOMETRY
for GIS data. - UUIDs stored as binary instead of text.
✅ Encrypted fields:
- If you need to encrypt/decrypt fields transparently on read/write → perfect place for a custom
AttributeConverter
orUserType
.
✅ Custom data serialization:
- Store objects as JSON or XML in a single text column.
- Store lists or sets as comma-separated strings (e.g., tags →
"tag1,tag2,tag3"
).
✅ Legacy schemas:
- When you don’t control the DB design but must map objects cleanly → custom type mapping can bridge the mismatch.
🔹 Examples in real apps
🔸 E-commerce → Money
value object → amount + currency mapped to two columns.
🔸 Multi-tenant SaaS → TenantId
as a value object → mapped to a UUID or long.
🔸 Auditing → automatically convert entity state into a JSON snapshot for storage.
📌 Key Takeaways
✅ Reach for custom types when you need to map non-standard Java-to-SQL representations, or encapsulate domain logic in value objects that can’t be stored as a simple field.
✅ Custom conversions help you keep your domain model clean without leaking persistence concerns into business logic.