Hibernate. Foreign key mapping by id

2019-08-14 17:22发布

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

}

2条回答
啃猪蹄的小仙女
2楼-- · 2019-08-14 17:55

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.

查看更多
不美不萌又怎样
3楼-- · 2019-08-14 18:10

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(){ ... }
查看更多
登录 后发表回答