Reputation: 337
One of my entity, contains a simple object which contains only two attributes. What is the recommended way of using hibernate/jpa annotation to map this entity.
For example, how to use annotation map Money in entity Report.
public class Report{
private long id;
private Money amount;
}
public class Money{
private BigDecimal value;
private String currency;
}
Upvotes: 0
Views: 66
Reputation: 9068
You could achieve it via this approach:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractBaseEntity {
public static final long INVALID_OBJECT_ID = -42;
@Version
private int version;
@Id
@SequenceGenerator(name = "sequence-object", sequenceName = "ID_MASTER_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence-object")
@Column(name = "id")
protected Long objectID = INVALID_OBJECT_ID;
public int getVersion() {
return version;
}
@Override
public long getObjectID() {
return objectID;
}
}
@Entity
public class Report extends AbstractBaseEntity {
@OneToOne(cascade=CascadeType.All)
private Money amount;
}
@Entity
public class Money extends AbstractBaseEntity {
@Column(name="value", nullable = false, scale = 3, precision = 13)
private BigDecimal value;
@Column(name="currency", nullable = false)
private String currency;
}
This way, you not only manage primary keys of one single entity / database table but for any other type in your domain.
If you require other parameters for the precision of the BigDecimal
value, you'll might be interested in this answer. For further details on the @Version
annotation check out this post.
Hope it helps.
Upvotes: 1