Hibernate OneToMany bi-directional ratio slow

I have the Sessions and Users classes with the following bi-directional OneToMany (generated using the sleep mode back-processing tool):

 public class Users { @OneToMany(fetch=FetchType.LAZY, mappedBy="users") public Set<Sessions> getSessionses() { return this.sessionses; } } public class Sessions { @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="USER_ID") public Users getUsers() { return this.users; } } 

And here is my code that creates a new session for the user:

 Session s = ...; Users user = (Users) s.createCriteria(Users.class) ./*restrictions...*/.uniqueResult(); Sessions userSession = new Sessions(); userSession.setUsers(user); s.save(userSession); user.getSessionses().add(userSession); // here getSessionses() has 2k records 

The user has 2k sessions, so the last line is very slow.

How can I associate a session with a user without getting a whole collection of sessions?

+4
source share
2 answers

Look at the Hibernate incremental download feature. You enable this by annotating your collection with @LazyCollection(LazyCollectionOption.EXTRA) . Here is this example , and there Set uses this one .

 public class Users { @OneToMany(fetch=FetchType.LAZY, mappedBy="users") @LazyCollection(LazyCollectionOption.EXTRA) public Set<Sessions> getSessionses() { return this.sessionses; } } 
+3
source

I'm not sure that hibernate will add this connection in both directions, but instead of adding Session to User set User to Session . This way you do not need to download every session.

+1
source

Source: https://habr.com/ru/post/1480902/


All Articles