A type adapter controls how a Java property is represented in database columns. Hibernate normally selects one from the property's Java type, but a mapping can name a different adapter. For example, a boolean can use a CHAR column containing Y or N instead of the default BIT mapping. section 6.3.1
Choose an adapter with the stored representation in mind:
- Use a named built-in adapter when its column type and values suit the schema. section 6.3.1
- Use a custom Hibernate UserType when a value needs its own conversion. Unlike a JPA converter, it can adapt any kind of entity property. section 6.3.3
- Treat Serializable fallback as a cautious choice: it stores a byte stream in VARBINARY, which may become hard to interpret long after the application changes. section 6.3.1
Adapting a monetary value
A MonetaryAmountUserType implements CompositeUserType and DynamicParameterizedType. A convertTo parameter selects a target currency; named type definitions supply USD and EUR configurations. Entity properties select those names with @Type and declare separate amount and currency columns with @Columns. section 6.3.3
Path: Ch06/mapping-value-types4/src/main/java/com/manning/javapersistence /ch06/model/Item.java @Entity public class Item { @NotNull @org.hibernate.annotations.Type( type = "monetary_amount_usd" ) @org.hibernate.annotations.Columns(columns = { @Column(name = "BUYNOWPRICE_AMOUNT"), @Column(name = "BUYNOWPRICE_CURRENCY", length = 3) }) private MonetaryAmount buyNowPrice; @NotNull @org.hibernate.annotations.Type( type = "monetary_amount_eur" ) @org.hibernate.annotations.Columns(columns = { @Column(name = "INITIALPRICE_AMOUNT"), @Column(name = "INITIALPRICE_CURRENCY", length = 3) }) private MonetaryAmount initialPrice; // . . . }
The entity mapping shows two properties using differently configured adapters and explicitly naming both columns for each monetary value. section 6.3.3
