Search code examples
javahibernatejpa

hibernate jpa, is there a simple way to get the dependent entity of a entity


I want to get dependent on other entities of a entity,for example:

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;
}

I get the entity who dependent on User, it is Role.I can parse @ManyToMany to get it,but if use xml configuration,I can not simply do that, so I would like to know if hibernate provides the API that can help me do this? thanks.


Solution

  • With JPA you can get all the information with the Metamodel, for example:

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

    Hibernate also provides some useful methods on the SessionFactory:

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