Home JPA retrieve entities relationships
Reply: 0

JPA retrieve entities relationships

alljinx
1#
alljinx Published in 2017-12-06 10:20:07Z

I am trying to retrieve the list of all entities containing relations that references the specified entity.

"Role" Entity :

@Entity
@Table(name="Role")
@Access(AccessType.PROPERTY)
public class Role implements Serializable {
    private String description;
    private Long roleId;

    @Column(name = "role_id")
    @Id
    public Long getRoleId() {}

    @Column(name = "description")
    public String getDescrition() {}
}

"User" Entity :

@Entity
@Table(name="users")
@Access(AccessType.PROPERTY)
public class User implements Serializable {
    private Long userId;
    private String name;
    private Role role;

    @Column(name = "user_id")
    @Id
    public Long getUserId() {}

    @ManyToOne()
    JoinColumn(name="role_id")
    public Role getRole() {}

    public String getName() {}
}

"Group" Entity :

@Entity
@Table(name="groups")
@Access(AccessType.PROPERTY)
public class User implements Serializable {
    private Long groupId;
    private String description;
    private Role role;

    @Column(name = "group_id")
    @Id
    public Long getGroupId() {}

    @ManyToOne()
    JoinColumn(name="role_id")
    public Role getRole() {}

    public String getDescription() {}
}

I need a that works like this :

List<Class<?>> entities = getEntityReferences(Role.class);
foreach (Class<?> entity : entities )
    System.out.println(entity.getName());

The output would be :

User
Group

I think JPA use something like this for the bean validations or cascade mechanics but I can't find a simple way to achieve this.

The only way I found by now is to iterate through all the annotations of all the entities (returned by "entityManagerFactory.getMetamodel().getEntities()") to look for relations (ManyToOne, OneToOne ect.). It seems a bit tedious, I'm sure there's a better way to do it...

Thank you all...

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.30274 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO