gpt4 book ai didi

hibernate - ManyToMany关联删除连接表条目

转载 作者:行者123 更新时间:2023-12-01 02:58:22 26 4
gpt4 key购买 nike

我使用这两个实体来创建一个新用户和它关联的组:

@Entity  
@Table(name="usertable")
@SuppressWarnings("serial")
@Searchable
public class User implements Serializable {

@GeneratedValue(generator="userIdSeq")
@SequenceGenerator(name="userIdSeq", sequenceName="usertable_id_seq")
@SearchableId
@Id
int id;

@SearchableProperty
String userId; // 'Unique identifier. It is formed using this fashion: ''prefix:identifier''
String userName; // Name used to log in the application.
String email; // User's email

@ManyToMany
@JoinTable( name="usergroup",
joinColumns=@JoinColumn(name = "userid", referencedColumnName="userId"),
inverseJoinColumns=@JoinColumn(name = "groupid")
)
List<Group> groups;

...
}

// Group
@Entity
@Table(name="grouptable")
public class Group implements Serializable {
@Id
String groupId // Unique identifier for group.
String description // Brief text describing the group purposes.

@ManyToMany(mappedBy="groups")
@Cascade(SAVE_UPDATE)
List<User> users

....
}

在数据库上:
用户表(id、userId、名称)
分组表(ID,描述)
用户组(用户 ID、组 ID、组 key )

将 Group 添加到组列表中,在 User 上调用 save 方法并观看 hibernate 将 usergoup 保存在一起是非常令人满意的。但是,当我在保存(用户)操作后检索用户时,我有一个大问题,即 hibernate 自动从用户组表中删除条目。

下面是生成删除用户组的测试序列
  • 保存新用户
  • 保存新组
  • 并将组列在用户
  • 保存用户
  • 从电子邮件中获取用户
  •     @Test    @Transactional    public void testGetUserByEmail(){        Session session = factory.getCurrentSession();         String email = "sarah.silverman@comedycentral.com";         User user = createUser();         user.setWeCanContact(true);         user.setPartnersCanContact(false);         user.setAgreedTerms(false);         user.setReferer("Laura");        String groupId = "AARP";         String description = "Appletalk Address Resolution Protocol";         Group group1 = new Group();         group1.setGroupId(groupId);         group1.setDescription(description);         session.save(group1);         session.flush();         user.getGroupLists().add(group1);         session.saveOrUpdate(user);         User testUser = userRepository.getUserByEmail(email);        assertNotNull(testUser);         assertEquals("It's not the correct email", email, testUser.getEmail());     }
        private User createUser(){
    Session session = factory.getCurrentSession();
    String userId = "UB:2010";
    String userPassword = "sarah";
    String realName = "Sarah Silverman";
    String email = "sarah.silverman@comedycentral.com";

    User user = new User();
    user.setUserId(userId);
    user.setUserName(email);
    user.setUserPassword(userPassword);
    user.setRealName(realName);
    user.setEmail(email);

    List<Group> emptyGroupLists = new ArrayList<Group>();
    user.setGroupLists(emptyGroupLists);
    Group group = new Group();
    group.setGroupId("ABC");
    group.setDescription("A for apple");
    user.getGroupLists().add(group);
    session.save(group);
    session.save(user);

    session.flush();
    return user;
    }
    // Repository Method to get user from email// //  @NamedQuery(name="user.findByEmail",//       query="SELECT u FROM User u " +//    "LEFT JOIN FETCH u.groupLists " +//              "WHERE upper(u.email) = :email")public User getUserByEmail(String email) {    Session session = sessionFactory.getCurrentSession();     Query query = session.getNamedQuery("user.findByEmail");    query.setParameter("email", email.toUpperCase());    User user = (User)query.uniqueResult();    return user; }

    Before executing step 5, usergroup with automatically removed like // SQL output

    Hibernate:
    delete
    from
    usergroup
    where
    userid=?

    我要注意的几件事;
    1. userid 不是用户对象的 pk。那会是问题吗?
    2. userid 和 groupid 映射的 usergroup 中的 manyTomany 映射
    3. 它不仅发生在测试中。它也在开发中。

    如何停止用户组的自动删除。用户组是非常重要的表,不应删除。任何帮助将非常感激。谢谢你。

    最佳答案

    让我们看看用户

    public class User {

    @Id
    @GeneratedValue
    private Integer id;

    @ManyToMany
    @JoinTable(name="USER_GROUP",
    joinColumns=@JoinColumn(name="USER_ID", referencedColumnName="USER_ID"),
    inverseJoinColumns=@JoinColumn(name="GROUP_ID")
    )
    private List<Group> groupList = new ArrayList<Group>();

    }

    现在我们的集团
    public class Group {

    @Id
    private String id;

    @ManyToMany(mappedBy="groupList")
    @Cascade(SAVE_UPDATE)
    private List<User> userList = new ArrayList<User>();

    }

    在继续之前,让我们简单地看一下 userList 字段
    // Group.java

    @ManyToMany(mappedBy="groupList")
    @Cascade(SAVE_UPDATE)
    private List<User> userList = new ArrayList<User>();

    @Cascade(SAVE_UPDATE) 表示

    Save Or Update each referenced User



    mappingBy="groupList"的意思是

    For each REFERENCED user, see whether it has a reference to me (Group object). If so, set up our bidirectional relationship. So if you want to link User and Group through USER_GROUP table, each REFERENCED user has to have a reference to a Group object.



    现在让我们看看 testGetUserByEmail 方法中发生了什么
    Group group = new Group(); 
    group.setId(groupId);

    // group.getUserList(); returns a empty List, right ?
    // As there is no User with reference to group in group.getUserList();
    // So NO LINK between Group and User through USER_GROUP table
    session.save(group);

    // It explains why your link is missing
    // You need to set up both sides
    user.getGroupLists().add(group);

    // Just save a User
    // Nothing else
    session.saveOrUpdate(user);

    在 createUser 方法中,您有与上图相同的场景

    所以我的建议是

    When using bidirectional relationship, ALWAYS use a add convenience method


    // Group.java
    public void addUser(User user) {
    user.getGroupList().add(this);

    getUserList().add(user);
    }

    // User.java
    public void addGroup(Group group) {
    group.getUserList().add(this);

    getGroupList().add(group);
    }

    问候,

    关于hibernate - ManyToMany关联删除连接表条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2080486/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com