是否有可能避免在 Hibernate 中使用字符串文字,例如在条件限制和投影中:
Criteria criteria = session.createCriteria(Employee.class)
.add(Restrictions.eq("name", "john doe"));
或
Projection p1 = Projection.property("name");
例如,在上面的代码片段中,将 "name"
替换为 something.name
,其中 something
包含 Employee 类的所有成员。
它会减少错误的发生,例如字符串中的错字。
编辑:将问题更新为更笼统而不是特定于标准。
最佳答案
您可以打开 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 提供商也支持它。
关于java - 如何避免 hibernate 中的字符串成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36643253/