【问题标题】:ORMLite + MySQL: how to find one matching record?ORMLite + MySQL:如何找到一条匹配的记录?
【发布时间】:2014-05-17 22:21:38
【问题描述】:

我有一个名为“Article”的 java 类,它使用 ORMLite 与 MySQL 数据库进行连接/通信。我的插入有效,但我有一个问题,只检索一篇文章(对应于 mysql 数据库表中的一行)给定一个“id”(在 mysql 数据库表中自动递增)。

看来我得用一个List变量来保存查询结果:

Dao<Article,String> articleDAO = DaoManager.createDao(connectionSource, Article.class);
List<Article> article = articleDAO.queryForEq("id", id); /* is there a method to find only one matching record and returns an Article type ? */

我想做这样的事情:

Article article = articleDAO.queryOne("id", id);

【问题讨论】:

  • 你可以做Article a = articleDAO.queryForId("1");每个例子。
  • 感谢邹邹。我只是要尝试这种方法。
  • 应该可以,我刚刚测试过;)
  • 是的!它也适用于我。非常感谢!

标签: java mysql ormlite


【解决方案1】:

你使用查询List&lt;Article&gt; article = articleDAO.queryForEq("id", id);,而不是这样想:

if (article != null && article.size() !=0){
  return article.get(0)
} else {
  return null;
}

【讨论】:

  • 谢谢,我刚刚阅读了 ORMLite 的 API,发现 queryForId(id) 可以为我工作。我会试一试,然后报告。
【解决方案2】:

文章文章 = articleDAO.queryOne("id", id);

呃,你读过online docs吗? dao.queryForId(id) 是到处引用的。它旨在返回与行的唯一 id 匹配的值,就像 dao.update(...)dao.refresh(...) 从数据库中更改和读取该行一样。

另外,还有一个dao.queryForFirst(preparedQuery),它从查询中获取第一个结果。

【讨论】:

    猜你喜欢
    • 2023-02-22
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多