valdodov
valdodov

Reputation: 1

How to use Hibernate annotations

I have following tables in in DB: Tables

and want to have hibernate @Entity ExchangeRates like followng POJO:

class ExchangeRates{
    List<Currency> currencies;
}

class Currency{
    Long Id;
    String name;
    List<Rate> exchangeRates;
}

class Rate{
    Currency currency;
    BibDecimal rate;
}

can any advice me how to do this with hibernate annotations?

Upvotes: 0

Views: 47

Answers (1)

Michael Seiler
Michael Seiler

Reputation: 650

If you have two Entities with a ManyToMany relationship you will have a JoinTable that references both.

The Table would e.g. look like this:

Name: EX_CUR
Column 1:CUR_ID
Column 2:EX_ID

And the Entities like this:

@Entity
@Table(name="currencies_fixed_exchange_rates")
class ExchangeRates{

    @Id
    Long id;

    @ManyToMany
    @JoinTable(
      name="EX_CUR",
      joinColumns=@JoinColumn(name="CUR_ID", 
      referencedColumnName="ID"),
      inverseJoinColumns=@JoinColumn(name="EX_ID", 
      referencedColumnName="ID"))
    List<Currency> currencies;
}

@Entity
@Table(name="currencies")
class Currency{

    @Id
    Long Id;

    @Column
    String name;

    @ManyToMany(mappedBy="currencies")
    List<Rate> exchangeRates;
}

@Entity
@Table
class Rate{

    @Id
    Long id;

    @OneToOne
    Currency currency;

    @Column
    BigDecimal rate;
}

Upvotes: 1

Related Questions