2016-04-15 55 views
2

是否有可能避免使用在休眠串literials,如在標準的限制和突起:如何避免hibernate中的字符串成員?

Criteria criteria = session.createCriteria(Employee.class) 
        .add(Restrictions.eq("name", "john doe")); 

Projection p1 = Projection.property("name");

例如,在上面的代碼段,以代替"name"something.name ,其中something包含Employee類的所有成員。

這會使它不易出錯,例如,字符串中的錯字。

編輯:更新問題是更一般的,而不是隻針對標準。

+0

你是否嘗試用''something.name「'替換''name''?如果是,您是否收到錯誤或什麼? –

+0

但我的問題是,我不知道應該是什麼東西? –

+0

請檢查我的答案,它應該幫助你。 –

回答

1

您可以創建一個員工常量類:

public class EmployeeConstants { 
     public static final String firstName= "firstname"; 
     public static final String lastName= "lastname"; 
     .... 
} 

,並調用領域爲:

Criteria criteria = session.createCriteria(Employee.class) 
        .add(Restrictions.eq(EmployeeConstants.firstName, "john doe")); 

其實EmployeeConstants.firstName返回firstname它必須是的字段名稱實體。

+0

我曾考慮過這個問題,但它比解決方案更適合解決問題。它肯定比在Hibernate代碼中使用字符串文本更好,但不如linq語法那樣優雅,因爲在對基礎進行更改時,它會更新Contants類的額外開銷。這似乎是最好的辦法,但如果這不是由Hibernate本地支持。 –

+0

@JohnSteed:是的,你說它比在hibernate代碼中使用字符串文字更好,似乎我們沒有更好的解決方案。 –

+0

但有一個更好的解決方案,實際上不止一個。 –

0

你的情況,你可以通過例如使用查詢:

Employee employee = new Employee(); 
employee.setName("john doe"); 
Example employeeExample = Example.create(employee); 

Criteria criteria = session.createCriteria(Employee.class).add(employeeExample); 
+0

感謝您的回覆。對不起,我的問題太具體了。我的意思是在整個Hibrenate的使用過程中避免使用字符串來指定成員。我已經更新了我原來的問題 –

3

您可以打開JPA的元模型生成並使用Criteria API將生成的類的字段用作類型和名稱安全的「文字」。 來自實例Hibernate docs

@Entity 
public class Order { 
    @Id 
    @GeneratedValue 
    Integer id; 

    @ManyToOne 
    Customer customer; 

    @OneToMany 
    Set<Item> items; 
    BigDecimal totalCost; 
    // standard setter/getter methods 
} 

@StaticMetamodel(Order.class) // <<<<<<<<<< this class gets generated for you 
public class Order_ { 
    public static volatile SingularAttribute<Order, Integer> id; 
    public static volatile SingularAttribute<Order, Customer> customer; 
    public static volatile SetAttribute<Order, Item> items; 
    public static volatile SingularAttribute<Order, BigDecimal> totalCost; 
} 
// type-safe and typo-proof building of query: 
CriteriaBuilder cb = entityManager.getCriteriaBuilder(); 
CriteriaQuery<Order> cq = cb.createQuery(Order.class); 
SetJoin<Order, Item> itemNode = cq.from(Order.class).join(Order_.items); 
cq.where(cb.equal(itemNode.get(Item_.id), 5)).distinct(true); 

這是在大的實體和複雜查詢的情況下,非常方便。唯一的缺點是它有時會變得非常冗長。
它是JPA標準,所以EclipseLink和其他JPA提供商也支持它。

+1

這應該是被接受的答案。 –

相關問題