6

在一些 JPA 注释中,我想直接在代码中使用字段名称来代替容易出错的字符串:

@javax.persistence.OrderBy(value = User_.registrationDate.getName())
public List<PlugConfig> getPlugConfigs() { ... }

但是上面不会编译,因为要获得名称,我必须使用不是常量表达式的函数(User_ 是生成的 JPA @StaticMetamodel)。

是否可以以任何方式使用元模型,或者我坚持直接字符串常量?有没有办法为元模型自动生成这样的字符串常量?(我正在使用 maven-processor-plugin 进行生成)

4

2 回答 2

5

现在,我的元模型类中的每个字段都有两个字段,例如:

public static final String _registrationDate="registrationDate";
public static volatile SingularAttribute<User, Date> registrationDate;   

为了让它工作,我重用了来自 JPAMetaModelEntityProcessor 的代码(不幸的是,简单地扩展这个类有问题)。我添加了这个方法:

    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);
        }
    }

}

我在每次发生之前调用它

ClassWriter.writeFile(entity, context);

对应的maven配置:

        <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>
于 2012-06-02T20:23:53.253 回答
0

我没有尝试过,但从我在完全其他上下文(不是 JPA)中阅读的内容来看,您可以尝试:

  • 指定一个自定义注释 (RetentionPolicy.SOURCE) 并注释您的实体类(或者您可以只依赖 @Entity 注释)
  • 编写一个注解处理器,它编写一个带有静态字段的类

例如

public class UserConstants{
    public static final String REGISTRATION_DATE = User_.registrationDate.getName(); 
}

这只是一个想法。我不知道它是否适合这种情况。

于 2012-05-31T20:59:32.700 回答