假设我正在处理 MyEntity
表,其中 name
字段必须是唯一的(但不是主键)。
我想使用 QueryDSL 定义 findByName
方法。
我当前的实现如下:
public MyEntity findByName(final String name) {
JPAQuery query = new JPAQuery(this.entityManager);
QMyEntity myEntity;
List<MyEntity> result = jpaQuery.from(myEntity).where(myEntity.name.eq(name)).list(myEntity);
if (result.isEmpty())
throw new EntityNotFoundException();
else if (result.size() == 1)
return result.get(0);
else
throw new PersistenceException();
}
我的解决方案是完成此任务的正确解决方案还是有更好的方法?
最佳答案
使用uniqueResult而是列表
:
public MyEntity findByName(final String name) {
JPAQuery query = new JPAQuery(this.entityManager);
QMyEntity myEntity;
MyEntity result = jpaQuery.from(myEntity).where(myEntity.name.eq(name)).uniqueResult(myEntity);
if (result == null)
throw new EntityNotFoundException();
else
return result;
}
关于java - 使用 QueryDSL 按唯一字段查找实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26176008/