I've started using Hibernate together with SpringSecurity and GrantedAuthorities.
When querying the database I'm getting wrong results now.
User:
@Entity
@Table
public class User implements UserDetails {
@Id
@GeneratedValue
private Long id;
@Column(unique = true, nullable = false)
private String username;
@Column(nullable = false)
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "user_authorities",
joinColumns = @JoinColumn(name = "userid"),
inverseJoinColumns = @JoinColumn(name = "authority")
)
private List<Authority> authorities = new ArrayList<>();
@OneToMany(mappedBy = "owner")
private List<Order> orders = new ArrayList<>();
}
Authority:
@Entity
@Table
public class Authority implements GrantedAuthority {
@Id
@Column(unique = true, nullable = false)
private String authority;
@ManyToMany(mappedBy = "authorities")
private List<User> users = new ArrayList<>();
}
Order:
@Entity
@Table(name = "Orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@ManyToOne
@JoinColumn(name = "owner_id")
private User owner;
}
The problem is that Hibernate now lists all Orders
multiple times, depending on how many Authorities
a User
has.
If a User
has 3 Authorities
and 2Orders
, the following 6 objects appear in my DAO:
+----------+---------+------------+
| Order id | User id | Authority |
+----------+---------+------------+
| 1 | 1 | ROLE_USER |
| 1 | 1 | ROLE_ADMIN |
| 1 | 1 | ROLE_TEST |
| 2 | 1 | ROLE_USER |
| 2 | 1 | ROLE_ADMIN |
| 2 | 1 | ROLE_TEST |
+----------+---------+------------+
This is the related Hibernate query:
@Transactional(readOnly = true)
public List<Order> getOrdersForUser(User user) {
return sessionFactory.getCurrentSession()
.createCriteria(Order.class)
.add(Restrictions.eq("owner", user))
.list();
}
Can someone provide insight on this behaviour? I don't think that's how Hibernate should work.