Jared
Jared

Reputation: 99

How to check hibernate mappings using reflection?

So, I realize this is out of the normal use case of Hibernate, but...

I am using java reflection to populate DTO classes that persist via Hibernate with annotation config. I need to reflexively find the @ManyToOne relation mappedBy attribute in order to set the back link from one to many.

Code:

class Router{
@OneToMany(targetEntity = Port.class, cascade = CascadeType.ALL, mapped = "router", fetch = FetchType.LAZY)
Collection<Port> ports;
}

class Port{
  @JsonBackReferene
  @ManyToOne(cascade = {CascadeType.ALL, fetch = FetchType.LAZY)
   Router router;
}

Reflexively (and recursively), I populate the DTOs starting from the Router. When the port has all of its attributes set (auto-negotiate, etc), it is returned to the Router to be added to the portList. The Port.router field is unset because I can't find a way to reflexively get the @OneToMany.mappedBy value, which would let me know which field in Port to set to the Router instance.

Any advice is much appreciated!!!

Thanks!

Upvotes: 1

Views: 1269

Answers (1)

Konstantin Solomatov
Konstantin Solomatov

Reputation: 10332

You can use reflection API for this. Something like this:

Class Cls = ... ;
cls.getField("xyz").getAnnotation(ManyToMany.class).mappedBy

Upvotes: 2

Related Questions