在JPA中,查詢單條記錄可以通過以下方式實現:
MyEntity entity = entityManager.find(MyEntity.class, id);
MyEntity entity = entityManager.createQuery("SELECT e FROM MyEntity e WHERE e.id = :id", MyEntity.class)
.setParameter("id", id)
.getSingleResult();
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<MyEntity> query = cb.createQuery(MyEntity.class);
Root<MyEntity> root = query.from(MyEntity.class);
query.select(root).where(cb.equal(root.get("id"), id));
MyEntity entity = entityManager.createQuery(query).getSingleResult();
以上是JPA中查詢單條記錄的幾種常用方式,開發者可以根據具體場景選擇合適的方法。