在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中查询单条记录的几种常用方式,开发者可以根据具体场景选择合适的方法。