Hibernate. Foreign key mapping by id

2019-08-14 17:25发布

问题:

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();

}

回答1:

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.



回答2:

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(){ ... }