【问题标题】:Find entity by unique field with QueryDSL使用 QueryDSL 通过唯一字段查找实体
【发布时间】:2014-10-03 08:52:58
【问题描述】:

假设我正在处理name 字段中的MyEntity 表,该字段必须是唯一的(但不是主键)。

我想使用 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();
}

为了完成这项任务,我的解决方案是正确的还是有更好的方法?

【问题讨论】:

    标签: java jakarta-ee jpa querydsl


    【解决方案1】:

    使用uniqueResult 代替list

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-17
      • 2020-03-27
      • 1970-01-01
      相关资源
      最近更新 更多