2016-09-24 48 views
2

我想依賴於實體的其他實體,例如依賴實體:休眠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; 
} 

我得到的實體誰依賴於用戶,它是Role.I可以解析@ManyToMany來獲取它,但是如果使用xml配置,我不能簡單地這樣做,所以我想知道hibernate是否提供了API來幫助我做到這一點?謝謝。

+0

看看'EntityPersister'。 [Here](http://stackoverflow.com/a/31544714/4754790)是使用它來獲取映射元數據的一個例子;獲取關聯實體類型的信息也應該相對容易。 –

+0

@Dragan Bozanovic我讀了'EntityPersister',它也很有用 – xiayouxue

回答

0

隨着JPA你可以得到所有的信息與元模型,例如:

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

Hibernate也提供了一個SessionFactory一些有用的方法:

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