hibernate jpa,是否有一种简单的方法来获取实体的依赖实体

时间:2016-09-24 16:06:45

标签: java hibernate jpa

我希望依赖于实体的其他实体,例如:

public class User {

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

    private String name;

    @ManyToMany(mappedBy = "users")
    private Set<Role> roles;
}

public class Role {

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

    private String name;

    @ManyToMany
    @JoinTable
    private Set<User> users;
}

我得到依赖于User的实体,它是Role.I可以解析@ManyToMany来获取它,但是如果使用xml配置,我不能简单地这样做,所以我想知道hibernate是否提供了API可以帮我这么做吗?感谢。

1 个答案:

答案 0 :(得分:1)

使用JPA,您可以使用Metamodel获取所有信息,例如:

entityManager.getMetamodel().entity(User.class).getCollection("roles");

Hibernate还在SessionFactory上提供了一些有用的方法:

hibernateSession.getSessionFactory().
    getClassMetadata(User.class).getPropertyType("roles") ...