【问题标题】:Problem in fetching data using CriteriaBuilder使用 CriteriaBuilder 获取数据的问题
【发布时间】:2018-10-07 04:56:49
【问题描述】:

ContactInfo 类的数据库中有一个表。现在我想找到 customerId = idisDeleted = false

的值
 private EntityManager entityManager;
 public ContactInfo findById(long id) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ContactInfo> criteria = builder.createQuery( ContactInfo.class );
    Root<ContactInfo> root = criteria.from(ContactInfo.class);
    criteria.select(root).where(
            builder.equal(root.get("customerId"), id),
            builder.equal(root.get("isDeleted"), false)
    );
    return entityManager.createQuery(criteria).getSingleResult();
}

联系信息类:

public class ContactInfo extends BaseInfo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long cntId;
    @Column(columnDefinition="TEXT",length=4000)
    private String data;
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="customer_id")
    private PersonalInfo customer;

    public ContactInfo(){ }
    public ContactInfo(Long id) {
        this.cntId = id;
    }
}

个人信息类:

public class PersonalInfo extends BaseInfo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long customerId;//
    private Long cardId;//
}

BaseInfo 类:

abstract public class BaseInfo {

    @CreatedDate
    private Date createdDate;
    @CreatedBy
    private String createdBy;
    @LastModifiedDate
    private Date modifiedDate;
    @LastModifiedBy
    private String modifiedBy;
    @Column(columnDefinition = "boolean default false", nullable = false)
    private boolean isDeleted;
}

如何绕过以下错误。提前致谢。 错误

2018-10-07 10:47:11.742 ERROR 1168 --- [nio-8082-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Unable to locate Attribute  with the the given name [customerId] on this ManagedType [com.exm.base.BaseInfo]; nested exception is java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [customerId] on this ManagedType [com.csinfotechbd.base.BaseInfo]] with root cause

【问题讨论】:

  • 请在您的问题中添加您的实体类ContactInfo
  • 请告诉我们ContactInfo类的代码。
  • 我已经添加了所有必要的类。请看看。
  • customerId 不是 ContactInfo 的一部分,但它是 PersonalInfo 类的一部分,因此您应该只从 PersonalInfo 类中获取 customerId。
  • 我正处于学习阶段。我对这些东西有一点了解。请你解释一下如何摆脱它或任何可以帮助我解决这个问题的资源。

标签: java hibernate hibernate-criteria


【解决方案1】:

您的 customerId 存在于 PersonalInfo 实体中,因此您的条件查询应如下所示。

criteria.select(root).where(
    builder.equal(root.get("customer").get("customerId"), id)
);

请试试这个。

希望这能解决你的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-04
    • 2013-10-08
    • 2020-03-02
    • 1970-01-01
    • 2019-08-23
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多