Andrey Frolov
Andrey Frolov

Reputation: 1534

Hibernate. Foreign key mapping by id

I want to create @ManyToOne mapping between Acount and Record. One account can have a lot of records. But i don't want to add Account field in Record class or vice versa. Could you please help me to describe this in annotations?

@Entity
public class Account {

  @Id
  ... getId();
}

@Entity
public class Record {

  @Id
  ... getId();

  @?????
  ... getAccountId();

}

Upvotes: 1

Views: 3282

Answers (2)

Jeremy
Jeremy

Reputation: 22435

If you don't want to add the foreign key constraints to either table, you can create a separate table with the constraints that allows you to make the relation.

accountId | recordId
--------------------
 1        | 2
 1        | 3
 2        | 4

With JPA...

@ManyToOne
@JoinColumn(table=TABLE_NAME_ABOVE,name="accountId")
public Account getAccount(){ ... }

Upvotes: 0

Riccardo Cossu
Riccardo Cossu

Reputation: 2739

Mapping entities to tables is the way Hibernate usually works, if you don't want the Account class in Record you can simply define accountId as long (or int, whichever is ok) and not annotate it unless you need a different column name. But I would suggest not to do it.

Upvotes: 2

Related Questions