How Magnum handles nested entities
masterMagnum does not support nested entity structures (e.g., a case class containing another case class as a field) via direct derivation. It only supports deriving flat entity class structures to ensure a clear mapping between Scala classes and SQL tables.
To represent relationships between entities, use foreign keys and opaque types with custom DbCodec implementations.
Example pattern for a relationship:
- Define an
opaque typefor the ID. - Implement a
DbCodecfor that opaque type usingbiMap. - Use the ID type in the parent entity and define the child entity as a separate
@Table.
@Table(H2DbType, SqlNameMapper.CamelToSnakeCase)
case class Company(
name: String,
addressId: AddressId,
)
opaque type AddressId = Long
object AddressId:
def apply(id: Long): AddressId = id
extension (id: AddressId)
def underlying: Long = id
given DbCodec[AddressId] =
DbCodec[Long].biMap(AddressId.apply, _.underlying)
@Table(H2DbType, SqlNameMapper.CamelToSnakeCase)
case class Address(
@Id id: AddressId,
street: String,
city: String,
zipCode: String,
country: String
) derives DbCodec