使用 NHibernate 查询

2024-03-29

我是 NHibernate 的新手,我正在尝试学习如何查询我的数据。

下面是配置 xml。仅显示食谱。

我希望能够通过输入的关键字按菜谱标题查询菜谱 还有成分名称中的成分。

例如,您可以输入“意大利面酒”。

这是我尝试过的,但给了我一个错误。

    hql = "from Recipe r " +
    "left join r.Images " +
    "inner join r.User " +
    "inner join r.Ingredients i " +
    "where i.IngredientName Like '%pasta%' OR i.IngredientName Like '%wine%' OR r.RecipeTitle Like '%pasta' OR r.RecipeTitle Like '%wine%'";

我也想加载集合。

我要查询对吗? 我需要能够根据我的搜索条件构建查询字符串。 这对我来说用 SQL 来说很容易。

Malcolm

  <class name="Recipe" table="Recipes" xmlns="urn:nhibernate-mapping-2.2">
    <id name="RecipeID" type="Int32" column="RecipeID">
      <generator class="identity" />
    </id>
    <property name="RecipeTitle" type="String">
      <column name="RecipeTitle" />
    </property>
    <property name="Completed" type="Boolean">
      <column name="Completed" />
    </property>
    <property name="ModifiedOn" type="DateTime">
      <column name="ModifiedOn" />
    </property>
    <property name="Rating" type="Double">
      <column name="Rating" />
    </property>
    <property name="PrepTime" type="Int32">
      <column name="PrepTime" />
    </property>
    <property name="CookTime" type="Int32">
      <column name="CookTime" />
    </property>
    <property name="Method" type="String">
      <column name="Method" />
    </property>
    <bag name="Images" inverse="true" cascade="all">
      <key column="RecipeID" />
      <one-to-many class="OurRecipes.Domain.RecipeImage, OurRecipes.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </bag>
    <many-to-one name="Category" column="CategoryID" />
    <bag name="Comments" inverse="true" cascade="all">
      <key column="RecipeID" />
      <one-to-many class="OurRecipes.Domain.Comment, OurRecipes.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </bag>
    <many-to-one name="User" column="EnteredByID" />
    <bag name="Ingredients" inverse="true" cascade="all">
      <key column="RecipeID" />
      <one-to-many class="OurRecipes.Domain.Ingredient, OurRecipes.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </bag>
  </class>

为了构建动态查询,我将使用条件 API。这使得动态查询更加稳定,因为您不需要字符串操作来构建它。

ICriteria query = Session.CreateCriteria(typeof(Recipe), "r")
  .CreateCriteria("Ingredients", "i", JoinType.InnerJoin)
  .Add(
    Expression.Disjunction() // OR
      .Add(Expression.Like("i.IngredientName", "%pasta%"))
      .Add(Expression.Like("i.IngredientName", "%wine%"))
      .Add(Expression.Like("r.RecipeTitle", "%pasta%"))
      .Add(Expression.Like("r.RecipeTitle", "%wine%")));

List<Recipe> result = query.List<Recipe>();

Edit:

对于急切加载,您可以设置 fetch-mode:

ICriteria query = Session.CreateCriteria(typeof(Recipe), "r")
  .SetFetchMode("Images", FetchMode.Join)
  .SetFetchMode("Comments", FetchMode.Join)
  .SetFetchMode("Ingredients", FetchMode.Join)

但我不会这样做因为你得到的结果乘以图像、评论和成分的数量。因此,如果您有 4 张图片、2 条评论和 12 种成分,您将获得 96 次食谱。您没有意识到这一点,因为 NHibernate 将这些东西重新组合在一起,但它会在应用程序和数据库之间产生流量。因此最好让 NHibernate 通过单独的查询来加载它。


又一编辑显示动态查询组合。

// filter arguments, all are optional and should be omitted if null
List<string> keywords;
TimeSpan? minCookingTime;
TimeSpan? maxCookingTime;
int? minRating;
int? maxRating;

ICriteria query = Session.CreateCriteria(typeof(Recipe), "r");

if (keyword != null)
{
  // optional join
  query.CreateCriteria("Ingredients", "i", JoinType.InnerJoin);

  // add keyword search on ingredientName and RecipeTitle
  var disjunction = Expression.Disjunction();
  foreach (string keyword in keywords)
  {
    string pattern = String.Format("%{0}%", keyword);
    disjunction
      .Add(Expression.Like("i.IngredientName", pattern))
      .Add(Expression.Like("r.RecipeTitle", pattern)); 
  }
  query.Add(disjunction)
}

if (minCookingTime != null)
{
  query.Add(Expression.Ge(r.CookingTime, minCookingTime.Value));
}
if (maxCookingTime != null)
{
  query.Add(Expression.Le(r.CookingTime, maxCookingTime.Value));
}

if (minRating != null)
{
  query.Add(Expression.Ge(r.Rating, minRating.Value));
}
if (maxRating != null)
{
  query.Add(Expression.Le(r.Rating, maxRating.Value));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 NHibernate 查询 的相关文章

随机推荐

  • 使用 SonarQube 进行多模块项目分析

    SonarQube Server 5 1 2 Sonar Runner 2 4 如提供的多模块项目 http docs sonarqube org display SONAR Analyzing with SonarQube Runner
  • 下划线充当分隔符 C# RTF Box

    我正在开发一个 Winforms 应用程序 并使用 RichTextBox 控件上的 Find 来查找要设置样式的特定关键字 由于某种原因 尽管指定了 WholeWord 标志 Find 似乎仍将其中带有下划线的单词视为 2 个单独的单词
  • Peewee MySQL 服务器消失了

    我用烧瓶和尿尿 有时 peewee 会抛出此错误 MySQL server has gone away error 32 Broken pipe Peewee 数据库连接 db PooledMySQLDatabase database pa
  • 对整数树求和 (Haskell)

    我正在尝试创建一个对非二叉整数树的值求和的函数 datastructures hs data Tree a Empty Node a Tree a deriving Eq Show myNums Num a gt Tree a myNums
  • 如何使基于列表的编辑器模板正确绑定到 POST 操作?

    我有一个模型 ApplicantBranchList 在更大的模型中用作属性 如下所示 Display Name Where would you want to work public ApplicantBranchList Prefere
  • 向 tm 结构添加一些间隔

    我有一个结构tm 我需要添加一些固定间隔 以xx年 xx月 xx天给出 到tm struct 有没有标准函数可以做到这一点 我使用的编译器是 Windows XP 上的 MSVC 2005 有两个转换时间格式的函数 mktime 哪个转换s
  • 组合选择器时,空格与没有空格的含义相同吗?

    在 CSS 中 选择器与空格的结合意味着后裔 http www w3 org TR CSS21 selector html descendant selectors 但在另一个答案中如何在CSS选择器中组合类和ID https stacko
  • phpStorm 与 php-cgi 的问题

    所以我最近换成了 ubuntu 我试图再次设置我的环境 我设法安装了 LAMP 和 phpmyadmin 和 phpstorm 但是我无法做的是从 phpStorm 运行 php 脚本 当我尝试运行该程序时 页面给我一个 502 Bad g
  • 从另一个页面链接到特定选项卡

    我有一个包含 3 个选项卡的表单 div class tabs ul class tabset li a class active span Shirts span a li li a href span Jeans span a li l
  • 带验证器的 Perl 工作流模块

    我正在尝试让 perl 工作流程模块工作 http search cpan org jonasbn Workflow http search cpan org jonasbn Workflow 我设法弄清楚它如何与工作流程 操作 条件等一起
  • 如何在 C++ 中对匿名对象使用运算符=?

    我有一个带有重载运算符的类 IPAddress IPAddress operator IPAddress other if this other delete data this gt init other getVersion other
  • 属性“dataSource”是必需的 java 中的错误(Spring)

    我正在开发一个网络应用程序Java 春季 我的java文件是这样的 try JdbcTemplate jt new JdbcTemplate dataSource System out println Connection jt toStr
  • getline 如何像使用 fgets 一样限制输入量

    GNU手册 https www gnu org software libc manual html node Line Input html 这段话来自 GNU 手册 警告 如果输入数据有空字符 您将无法辨别 所以 除非您知道数据不能包含空
  • 有什么理由仍然对数据库表和列使用蛇形命名法?

    当我开始数据库设计时 出于某种原因 建议您始终对表和列使用蛇形命名法 my table name 我认为在 MySQL 中尤其如此 原因是在某些情况下会丢失或强制使用大写 快进到今天 我看到很多人使用 Pascal Case MyTable
  • Windows 或 Linux 上的 Objective C

    我想学习 Objective C 但没有 Mac 如何在 Windows 或 Linux 上编译 obj c 我更喜欢 Windows 但 Linux 也可以 GCC 有一个 Objective C 编译器 您可能还想调查GNUStep h
  • 在 Maven/Java 项目中创建资源

    如何创建资源 使其位于我的项目的资源文件夹中 下面 test txt 是我要创建的文件 但变量 url为空 因此我无法获取要创建的文件的路径 URL url HashArray class getResource test txt File
  • 如何在C++中提取数字的数字?

    基本上我想做一个小程序 当你输入一个数字 比如145 时 它会读取3位数字并打印最大的一位 int a b c 最大值 cout lt lt Enter a b and c cin gt gt a gt gt b gt gt c max a
  • 如何使 python 进程以正确的进程名称运行?

    我在 Python 中有一些长期进程和临时进程 虽然 shell 和 C 程序以自己的名称运行 但所有 Python 进程都以 python filename py 运行 这使得识别进程变得困难 如何使 python 进程在 Linux 中
  • Angular:将curl 转换为Angular $http POST 请求

    我有这条卷曲线 curl X POST H content type application json H AUTH TOKEN vLC4grMuKbtbamJL3L6x localhost 8080 v1 segments appkey
  • 使用 NHibernate 查询

    我是 NHibernate 的新手 我正在尝试学习如何查询我的数据 下面是配置 xml 仅显示食谱 我希望能够通过输入的关键字按菜谱标题查询菜谱 还有成分名称中的成分 例如 您可以输入 意大利面酒 这是我尝试过的 但给了我一个错误 hql