Sad*_*our 10 persistence jpa java-ee metamodel
我有一个持久对象(Action)和自动生成的数据模型(Action_).通过拥有Action类的对象和SingularAttribute的实例,是否可以获得与给定的SingularAttribute相对应的字段?
我需要一个这样的函数:
public S getValue(T object,SingularAttribute<T,S> attribute);
Run Code Online (Sandbox Code Playgroud)
我的实体类(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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的元模型类(Action_.java):
@StaticMetamodel(Action.class)
public class Action_ {
public static volatile SingularAttribute<Action, Long> id;
public static volatile SingularAttribute<Action, String> name;
}
Run Code Online (Sandbox Code Playgroud)
Ric*_*ich 10
正如JB Nizet建议的那样,你可以使用getJavaMember.我发现我不需要将私有字段设置为可访问,也许Hibernate已经这样做了.
如果这有用,这里有一些适合我的代码:
/**
* 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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用该getJavaMember()方法获取该成员,然后测试该成员是否为a Field或a Method,并使用反射访问该字段或在该对象上调用该方法.
在访问/调用它之前,您可能必须使该字段或方法可访问.而且您还必须处理对象的原始类型转换.
主要问题是:你为什么需要这个?
如果仅为此特定实体类需要它,则只需在属性名称上使用开关并返回适当的值:
switch (attribute.getName()) {
case "name":
return action.getName();
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7162 次 |
| 最近记录: |