繁体   English   中英

如何在不删除映射表中先前数据的情况下使用 Hibernate 或 JPA 建立多对多关系

[英]How to do many-to-many relationship without deleting the previous data in mapping table using Hibernate or JPA

我有 2 个实体: User.javaPushNotification.java和名为userpushnotification的映射表,其中发生多对多映射。 userpushnotification 表中的现有数据对我来说很重要。 因此,如果我尝试为推送通知(id=2)添加用户(比如说 id=5,6,7), hibernate会删除关系表中推送通知(id=2)的先前数据,然后为此添加新用户推送通知(id=2)。
我需要将所有记录保存在关系表中。 那么我如何限制 Hibernate/JPA 只执行插入查询而不是执行删除和插入查询。 简而言之,我只想将 append 数据放在关系表中,而不是覆盖。

用户.java:-

@Entity
@Table(name = "user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "id")
    @GenericGenerator(name = "gen", strategy = "identity")
    @GeneratedValue(generator = "gen")
    private long id;
    @Column(name = "username")
    private String username;
    @Column(name = "password")
    private String password;
    @Column(name = "authkey")
    private String authKey;

    @ManyToMany(fetch = FetchType.EAGER, mappedBy = "users")
    private Set<PushNotifications> pushNotifications = new HashSet<PushNotifications>();

PushNotifications.java:-

@Entity
@Table(name = "pushnotifications", uniqueConstraints =     @UniqueConstraint(columnNames = { "id" }))

public class PushNotifications implements Serializable {
@Id
@Column(name = "id")
@GenericGenerator(name="gen",strategy="identity")
@GeneratedValue(generator="gen")
private long id;

@Column(name = "shortdescription")
private String shortDescription;

@Column(name = "title")
private String title;

@JsonIgnore
@ManyToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)
@JoinTable(name = "userpushnotifications", 
joinColumns = {@JoinColumn(name = "pushnotificatoinId") }, 
inverseJoinColumns = { @JoinColumn(name = "userId") })
private Set<User> users = new HashSet<User>();

    public Set<User> getUsers() {
    return users;
}

public void setUsers(Set<User> users) {
    this.users = users;
}

当我尝试这样做时:

   PushNotifications notifications = iNotificationService
                    .getNotification(notificationId);
                    Set<User> newUsers = new HashSet<User>();
          newUsers .add(newUserToBeNotified_1);
          newUsers .add(newUserToBeNotified_2);

    notifications.setUsers(newUsers);
sessionFactory.getCurrentSession().merge(notifications);

在这里,我想为该通知类型添加 2 个用户,在关系表中已经有一个用于该通知类型的用户。 Hibernate 执行这些查询:

Hibernate: 
    delete 
    from
        userpushnotifications 
    where
        pushnotificatoinId=? 
        and userId=?
Hibernate: 
    insert 
    into
        userpushnotifications
        (pushnotificatoinId, userId) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        userpushnotifications
        (pushnotificatoinId, userId) 
    values
        (?, ?)

所以,我希望你明白我,我不希望 hibernate 进行删除操作。 请帮我解决这个问题,寻找答案......在此先感谢。

您可以为此使用Blaze-Persistence ,它在 JPA 之上工作,并为 collections 的 DML 操作提供支持。 查询可能如下所示

criteriaBuilderFactory.insertCollection(entityManager, PushNotifications.class, "users")
    .fromIdentifiableValues(User.class, "u", newUsers)
    .bind("id", notification.getId())
    .bind("users").select("u")
    .executeUpdate();

按照文档中的描述设置 Blaze-Persistence 后,您可以创建如下存储库:

@Component
class MyRepository {
  @Autowired CriteriaBuilderFactory cbf;
  @Autowired EntityManager em;

  public void addUsers(Collection<User> newUsers) {
    cbf.insertCollection(em, PushNotifications.class, "users")
    .fromIdentifiableValues(User.class, "u", newUsers)
    .bind("id", notification.getId())
    .bind("users").select("u")
    .executeUpdate();
  }
}

这将只向连接表发出插入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM