# Best practice to migrate DetachedCriteria to JPA Criteria API

**URL:** <https://discourse.hibernate.org/t/best-practice-to-migrate-detachedcriteria-to-jpa-criteria-api/6731>\
**Category:** Hibernate ORM\
**Created:** [October 6, 2022, 8:18am UTC](https://discourse.hibernate.org/t/best-practice-to-migrate-detachedcriteria-to-jpa-criteria-api/6731 "2022-10-06T08:18:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Malte](https://avatars.discourse-cdn.com/v4/letter/m/ce7236/32.png) [@Malte](https://discourse.hibernate.org/u/Malte)\
**Post date:** [October 6, 2022, 8:18am UTC](https://discourse.hibernate.org/t/best-practice-to-migrate-detachedcriteria-to-jpa-criteria-api/6731/1 "2022-10-06T08:18:11Z")

</div>

We face issues by migrating a huge legacy project to the JPA Criteria API in Hibernate 6 due to massive usage of the removed DetachedCriteria. So far i did not find any information about how to migrate the DetachedCriteria into the JPA Criteria API. Maybe there is just no “simple” migration available. If anyone has done the migration of the DetachedCriteria already, maybe he can share some hints/ideas how they have done it. Any help is highly appreciated.

---

<div class="post-metadata">

**Author:** ![beikov](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.hibernate.org/beikov/32/258_2.png) [@beikov](https://discourse.hibernate.org/u/beikov)\
**Post date:** [October 6, 2022, 10:38am UTC](https://discourse.hibernate.org/t/best-practice-to-migrate-detachedcriteria-to-jpa-criteria-api/6731/2 "2022-10-06T10:38:21Z")

</div>

The use of `DetachedCriteria` can usually be wrapped into custom classes e.g.

```java
DetachedCriteria query = DetachedCriteria.forClass(Employee.class);
query.add(Property.forName("name").eq("John Doe"));

```

can be encapsulated as e.g. `Specification`

```java
Specification<Employee> spec = (root, query, cb) -> {
    return cb.equal( root.get("name"), "John Doe" );
};

```

Where `Specification` is an interface like this.

```java
interface Specification<T> {
    Predicate toPredicate(Root<T> queryRoot, CriteriaQuery<T> query, CriteriaBuilder cb);
}

```

which you can call like:

```auto
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> query = cb.createQuery(Employee.class);
Root<Employee> root = query.from(Employee.class);
query.where( specification.toPredicate(root, query, cb) );
TypedQuery<Employee> typedQuery = entityManager.createQuery(query);
List<Employee> list = typedQuery.getResultList();

```
