Spring GrantedAuthorities和相关对象的Hibernate问题

时间:2014-12-28 23:22:27

标签: java mysql spring hibernate spring-security

我已经开始将Hibernate与SpringSecurity和GrantedAuthorities一起使用。

查询数据库时,我现在收到了错误的结果。

用户:

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

机关:

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

订单:

@Entity
@Table(name = "Orders")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "owner_id")
    private User owner;
}

问题是Hibernate现在多次列出所有Orders,具体取决于Authorities User的{​​{1}}个。{/ p>

如果User有3 Authorities和2 Orders,则我的DAO中会显示以下6个对象:

+----------+---------+------------+
| 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  |
+----------+---------+------------+

这是相关的Hibernate查询:

@Transactional(readOnly = true)
public List<Order> getOrdersForUser(User user) {

    return sessionFactory.getCurrentSession()
            .createCriteria(Order.class)
            .add(Restrictions.eq("owner", user))
            .list();

}

有人可以提供有关此行为的见解吗?我不认为Hibernate应该如何运作。

1 个答案:

答案 0 :(得分:0)

你可以尝试:

return sessionFactory.getCurrentSession()
        .createCriteria(Order.class)
        .add(Restrictions.eq("owner", user))
        .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
        .list();

看看这个answer