Multi-user recording

I use these two objects to create a new user and group it:

@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 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 .... } 

In the database: usertable (id, userId, name) grouptable (id, description) usergroup (userid, groupid, groupkey)

It is very convenient to add a group to the list of groups, call the save method on the user and watch the hibernation mode while saving usergoup togehter. However, I have a big hibernation problem that automatically automatically deletes an entry from the user group table when I retrieve the user after the save (user) operation.

Here is a test sequence that generates a user group deletion

  • save new user
  • save new group
  • And a group to display in the user
  • save user
  • get user email
  @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 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 performing step 5, the user group is automatically deleted // SQL Exit

 Hibernate: delete from usergroup where userid=? 

A few things I should note; 1. userid is NOT a pk user object. Would this be a problem? 2. Multidimensional display in a user group, displayed by user identifiers and groupid 3. This happens not only in the test. This is also in development.

How to stop automatic deletion of a user group. A user group is very important and should not be deleted. Any help is appreciated. Thanks.

+4
source share
1 answer

Take a look at User

 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>(); } 

Now our group

 public class Group { @Id private String id; @ManyToMany(mappedBy="groupList") @Cascade(SAVE_UPDATE) private List<User> userList = new ArrayList<User>(); } 

Before continuing, let's look at the userList field in a nutshell

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

@Cascade (SAVE_UPDATE) means

Save or update each specified user

mappedBy = "groupList" means

For each REFERENCED user, see if he has a link to me (Group object). If so, set up our bidirectional relationship. Therefore, if you want to associate a user and a group through the USER_GROUP table, each REFERENCED user must have a reference to the Group object.

Now let's see what happens in the testGetUserByEmail method

 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); 

In the createUser method, you have the same script as above.

So my advice

When using a bi-directional relationship, ALWAYS use the convenience adding 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); } 

Yours faithfully,

+3
source

All Articles