In some JPA annotations I want to use field names directly in code in place of error-prone strings:
@javax.persistence.OrderBy(value = User_.registrationDate.getName())
public List<PlugConfig> getPlugConfigs() { ... }
But the above won't compile because to get name I have to use function that is not constant expression (User_ is generated JPA @StaticMetamodel).
Is it possible to use metamodel for this in any way or have I stick to direct string constants? Is there any way to automatically generate such string constants for metamodel? (I am using maven-processor-plugin for generation)
A static metamodel is a series of classes that "mirror" the entities and embeddables in the domain model and provide static access to the metadata about the mirrored class's attributes.
Interface SingularAttribute<X,T> Superinterfaces: Attribute<X,T> , Bindable<T> Instances of the type SingularAttribute represents persistent single-valued properties or fields. Class<T> getBindableJavaType() Return the Java type of the represented object.
Now I get two fields for every field in my metamodel class, for example:
public static final String _registrationDate="registrationDate";
public static volatile SingularAttribute<User, Date> registrationDate;
To get this working I reused code from JPAMetaModelEntityProcessor (unfortunatelly there was problem with simply extending this class). I've added this method:
private void addFieldsNamesAsStrings(MetaEntity entity) {
if (entity instanceof AnnotationMetaEntity) {
AnnotationMetaEntity aentity = (AnnotationMetaEntity) entity;
List<MetaAttribute> newMembers = new ArrayList<MetaAttribute>();
for (final MetaAttribute ma : entity.getMembers()) {
MetaAttribute nma = new AnnotationMetaAttribute(aentity, null,
null) {
public String getDeclarationString() {
return new StringBuilder()
.append("public static final String ")
.append(getPropertyName()).append("=\""+ma.getPropertyName()+"\";")
.toString();
}
@Override
public String getPropertyName() {
return "_"+ma.getPropertyName();
}
@Override
public String getMetaType() {
return null;
}
};
newMembers.add(nma);
aentity.mergeInMembers(newMembers);
}
}
}
which I invoked before every occurance of
ClassWriter.writeFile(entity, context);
Corresponding maven configuration:
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<processors>
<processor>
com.company.MyProcessor
</processor>
</processors>
<outputDirectory>target/modelgen/src/main/java</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With