使用CriteriaUpdate查询时如何避免使用硬编码attributeName?

时间:2016-08-31 04:36:31

标签: java hibernate jpa

我有一个实体:

@Entity
@Table
public class ClassA{
    public static final String COL_VERSION = "VersionABC";
    public static final String COL_DATA = "DataABC";

    @Column(name = COL_VERSION)
    private String version;

    @Column(name = COL_DATA)
    private String data;

}   

在我的DAO中:

EntityManager mgr = getEntityManager();
CriteriaBuilder builder = mgr.getCriteriaBuilder();
CriteriaUpdate<ClassA> criteriaUpdate = builder.createCriteriaUpdate(ClassA.class);
Root<ClassA> root = criteriaUpdate.from(ClassA.class);
criteriaUpdate.set(root.get("data"), newData);
if (//condition){
    criteriaUpdate.set(root.get("version"), newVersion);    
}

mgr.createQuery(criteriaUpdate).executeUpdate();

此代码有效,但如何使用ClassA.COL_VERSIONClassA.COL_DATA而不是使用硬代码&#34;数据&#34;和&#34;版本&#34; ?

2 个答案:

答案 0 :(得分:2)

try like this it should be _. instead of ._


EntityManager mgr = getEntityManager();
CriteriaBuilder builder = mgr.getCriteriaBuilder();
CriteriaUpdate<ClassA> criteriaUpdate = builder.createCriteriaUpdate(ClassA.class);
Root<ClassA> root = criteriaUpdate.from(ClassA.class);
criteriaUpdate.set(root.get(ClassA_.data), newData);
if (//condition){
    criteriaUpdate.set(root.get(ClassA_.version), newVersion);    
}

mgr.createQuery(criteriaUpdate).executeUpdate();

参考http://www.programcreek.com/java-api-examples/index.php?api=javax.persistence.criteria.CriteriaUpdate

答案 1 :(得分:1)

您可以使用可以自动生成的元模型类。如果您使用maven来控制依赖项,那么添加此插件将为您生成元模型类。

<plugin>
    <groupId>org.bsc.maven</groupId>
    <artifactId>maven-processor-plugin</artifactId>
    <version>2.2.4</version>
    <executions>
     <execution>
       <id>process</id>
       <goals>
         <goal>process</goal>
       </goals>
       <phase>generate-sources</phase>
       <configuration>
         <processors>
           <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
         </processors>
       </configuration>
     </execution>
    </executions>
    <dependencies>
     <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-jpamodelgen</artifactId>
       <version>5.2.2.Final</version>
     </dependency>
    </dependencies>
</plugin>

生成元模型类后,您可以使用属性名称,如...

root.get(ClassA_.data)代替root.get("data")