JPA ManyToMany只坚持一方

时间:2014-09-25 19:02:37

标签: java spring jpa many-to-many

我有关于ManyToMany与Radio关系的用户表,如下表所示。在此关系中,只有方法saveUser在关系表中持久存在。总而言之,USER和RADIO_USER表中只保留了优势边。我如何坚持对方?

表USER:

+--------------------+--------------+------+-----+-------------------+----------------+
| Field              | Type         | Null | Key | Default           | Extra          |
+--------------------+--------------+------+-----+-------------------+----------------+
| user_account_id    | bigint(20)   | NO   | PRI | NULL              | auto_increment |
| name               | varchar(255) | YES  |     | NULL              |                |
+--------------------+--------------+------+-----+-------------------+----------------+

表RADIO:

+-----------------------+---------------+------+-----+-------------------+----------------+
| Field                 | Type          | Null | Key | Default           | Extra          |
+-----------------------+---------------+------+-----+-------------------+----------------+
| radio_id              | bigint(20)    | NO   | PRI | NULL              | auto_increment |
| name                  | varchar(128)  | NO   |     | NULL              |                |
+-----------------------+---------------+------+-----+-------------------+----------------+

表RADIO_USER:

+--------------------+------------+------+-----+-------------------+----------------+
| Field              | Type       | Null | Key | Default           | Extra          |
+--------------------+------------+------+-----+-------------------+----------------+
| account_radio_id   | bigint(20) | NO   | PRI | NULL              | auto_increment |
| radio              | bigint(20) | YES  | MUL | NULL              |                |
| user_account       | bigint(20) | YES  | MUL | NULL              |                |
+--------------------+------------+------+-----+-------------------+----------------+

USER实体:

@ManyToMany
@JoinTable(name = "RADIO_USER",
    joinColumns = {@JoinColumn(name = "user_account", referencedColumnName = "user_account_id")},
    inverseJoinColumns = {@JoinColumn(name = "radio", referencedColumnName = "radio_id")})
List<Radio> radios;

@Transactional
public void saveUser(User user) {
    user.setRadios(radioDao.getAll(Radio.class));
    entityManager.persist(user);
}

RADIO实体:

@ManyToMany(mappedBy="radios")
List<User> users;

@Transactional
public void saveRadio(Radio radio) {
    radio.setUsers(userDao.getAllUsersByRole(User.Role.ROLE_ADMIN));
    entityManager.persist(radio)
}

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

这是因为关系是双向的,对于Hibernate,所有者方是用于知道存在关联的一方。然后为此,我需要使用此代码:

@Transactional
public void save(Radio radio) {
    List<User> users = userDao.getAllUsersByRole(User.Role.ROLE_ADMIN);

    for (User user : users) {
        user.getRadios().add(radio);
    }

    radio.setUsers(users);
    entityManager.persist(radio)
}

有关详细信息,请参阅@ManyToMany(mappedBy = “foo”)