0

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;

}
MWiesner
  • 8,868
  • 11
  • 36
  • 70
Hirantha
  • 337
  • 1
  • 4
  • 14
  • https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#embeddables – JB Nizet May 18 '19 at 17:15

1 Answers1

1

You could achieve it via this approach:

General concepts first

@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;
    }
}

Specific aspects second

@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.

MWiesner
  • 8,868
  • 11
  • 36
  • 70
  • This was my initial idea. But example, apart from Report entity, there are several such entities which contain Money? I think then this will not be the suitable solution. – Hirantha May 22 '19 at 21:09
  • This won‘t be a problem. You can refer to `Money` from other/different entities as well. Each time you do, this will just be another relationship which will have a Foreign Key in the corresponding Table in the database. Go try it. – MWiesner May 23 '19 at 04:49