I am rather new to Java. I'd like to know if it's possible to reference a method or property in Java. This is not specific to Hibernate ORM but just to give you an idea, the following example is written as Hibernate entity classes.
@Entity(name = "Person")
public static class Person {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "author")
private List<Book> books = new ArrayList<>();
}
@Entity(name = "Book")
public static class Book {
@Id
private Long id;
private String title;
@NaturalId
private String isbn;
@ManyToOne
private Person author;
}
The Person::books
property has an OneToMany
annotation with mappedBy
set to "author"
, which eventually references the Book::author
property at compile time. I believe this is possible thanks to Java's powerful reverse-engineering features a.k.a Reflection
. This is great, but to make things even easier and debuggable, instead of putting a String value as the mappedBy
value, I would like to use put a reference to the Book::author
. This will ensure we're not referencing an invalid property on the fly (IDE-friendly). If we change the string to "authors"
by mistake we would not know it's invalid unless we compile the code.
So the preferred code for the OneToOne
annotation would look like this:
@OneToMany(mappedBy = Book::author)
private List<Book> books = new ArrayList<>();
I believe method referencing exists in Objective-C. (and JavaScript too in a hacky way).
As I said, the question is if Java has a method/property referencing feature or any hacks to do this? It's not specific to Hibernate ORM. I am talking about a language feature in general.