There is User Entity:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
...
@Column(nullable = false)
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
public Set<UserPermission> permissions;
}
There is permission entity:
@Entity
@Table(name = "user_permissions", indexes = {@Index(unique = true, columnList = "id")})
public class UserPermission {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", referencedColumnName = "id")
public User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "target_user_id", referencedColumnName = "id")
public User targetUser;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "other_entity", referencedColumnName = "id")
public OtherEntity otherEntity;
}
There is User Entity: @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long id; ... @Column(nullable = false) @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") public Set<UserPermission> permissions; } There is permission entity: @Entity @Table(name = "user_permissions", indexes = {@Index(unique = true, columnList = "id")} ) public class UserPermission { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id", referencedColumnName = "id") public User user; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "target_user_id", referencedColumnName = "id") public User targetUser; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "other_entity", referencedColumnName = "id") public OtherEntity otherEntity; } I use this code to fetch user entity:
... get session
... open transaction
final User user = session.find(User.class, id);
final Set<UserPermission> userPermissions = user.permissions;
for (UserPermission permission: userPermissions) {
}
... close transaction
Look at the comment in code above:
It means, that without any calls to targetUser, hibernate fetches it. That's really strange. This behavior really slows down performance of my application. My assumption: Hibernate just can't proxy two similar objects in one entity (i mean, user and targetUser have the same class, hibernate cannot proxy both objects and thats why it fetches targetUser immediately) How to solve this problem? Any suggestions? |