簡體   English   中英

Hibernate - 如何持久化多對多實體

[英]Hibernate - How to persist many to many entity

我有 2 個實體。 用戶和角色。 它們之間的關系是多對多單向的。

 @ManyToMany(fetch = FetchType.LAZY)
    @ToString.Exclude
    @JoinTable(name = "uber_user_role",
        joinColumns        = @JoinColumn(name = "uber_user_id"),
        inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles = new HashSet<>();

當持久化一個新的 User 實體時,ID 為 1 的 Role 實體應該與 User 相關聯。 到目前為止,我的代碼如下所示:

Role role = em.getReference(Role.class, 1L);
        user.getRoles().add(role);
        em.persist(user);
 

它可以工作,但會生成 3 個 sql 語句

  1. Select 獲取角色的語句 object
  2. 用於插入新用戶實體的插入語句
  3. 在聯結表中插入它們之間的關系的插入語句

有沒有更好的方法來實現這種行為? 我認為第一個 select 語句是多余的? 我們能否改為獲得角色 object 的代理,然后只進行 2 次插入?

First up all the user and role mostly have oneToMany relationship.

Second thing above you mention like three steps we need to follow there is no change.

But, the role object selection you can get role object reference instead of getting object.

In hibernate JPA repository queryfindById it will help you to get object reference.

暫無
暫無

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

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