How to get the display value of a SingularAttribute constant object?

I have a persistent object (Action) and an automatically generated data model (Action_). Having an Action class object and a SingularAttribute instance, is it possible to get a field corresponding to this SingularAttribute?

I need a function like this:

public S getValue(T object,SingularAttribute<T,S> attribute); 

My entity class (Action.java):

 @Entity @Table(name="ACTION") public class Action implements Serializable { private long id; private String name; public Action() { } @Id @Column(unique=true, nullable=false, precision=6) public long getId() { return this.id; } public void setId(long id) { this.id = id; } @Column(length=50) public String getName() { return this.name; } public void setName(String name) { this.name = name; } } 

My metamodel class (Action_.java):

 @StaticMetamodel(Action.class) public class Action_ { public static volatile SingularAttribute<Action, Long> id; public static volatile SingularAttribute<Action, String> name; } 
+8
java-ee jpa persistence metamodel
source share
2 answers

You can use the getJavaMember() method to get the member, and then check if this element is Field or Method , and access the field or call the object's method using reflection.

You will probably need to open access to this field or method before calling him / her. And you will also have to handle primitive type conversion to objects.

The main question: why do you need this?

If you only need this for this entity class, you can simply use the attribute name switch and return the appropriate value:

 switch (attribute.getName()) { case "name": return action.getName(); ... } 
+4
source share

As JB Nizet suggested, you can use getJavaMember . I found that I did not need to set private access fields, perhaps Hibernate already did this.

In case this is useful, here is some code that works for me:

 /** * Fetches the value of the given SingularAttribute on the given * entity. * * @see http://stackoverflow.com/questions/7077464/how-to-get-singularattribute-mapped-value-of-a-persistent-object */ @SuppressWarnings("unchecked") public static <EntityType,FieldType> FieldType getValue(EntityType entity, SingularAttribute<EntityType, FieldType> field) { try { Member member = field.getJavaMember(); if (member instanceof Method) { // this should be a getter method: return (FieldType) ((Method)member).invoke(entity); } else if (member instanceof Field) { return (FieldType) ((Field)member).get(entity); } else { throw new IllegalArgumentException("Unexpected java member type. Expecting method or field, found: " + member); } } catch (Exception e) { throw new RuntimeException(e); } } 
+8
source share

All Articles