簡體   English   中英

JPA多對一關系

[英]JPA many to one relation

我有一個關於ManyToOne關系的問題。 假設我有2個bean:

@Entity
@Table(name = "accounts")
public class Account {
     @Id
     @Column(name = "account_id")
     private int account_id;
}


@Entity
@Table(name = "broker_account")
public class BrokerAccount {

    @Id
    @Column(name = "broker_account_id")
    private int broker_account_id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="account_id", referencedColumnName = "account_id")
    private Account account;
}

我正在查詢下面的實體(普通獲取所有查詢)

entityManager.createQuery("from BrokerAccount", BrokerAccount.class)

我認為如果我查詢BrokerAccount實體,默認情況下,Account對象上將填充account_id列,因為它也存在於BrokerAccount表中,但是所有Account字段均為空。

我是否缺少某些內容,是否也應該在BrokerAccount實體本身上定義此字段/列以獲取其價值?

您已將Account關聯定義為@ManyToOne(fetch = FetchType.LAZY) 這意味着在執行entityManager.createQuery("from BrokerAccount", BrokerAccount.class) ,該Account將沒有任何entityManager.createQuery("from BrokerAccount", BrokerAccount.class) ,並且此時將不會獲​​取其數據。

為了使持久性提供程序獲取Account數據,您需要使用相同的事務處理方法與引用進行交互,例如,fe: brokerAccount.getAccount().getAccountId();

如果只想為fk重復一列,可以執行以下操作:

@Column(name = "account_id", insertable=false, updatable=false)
private int account_id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM