NHibernate 在 CreateSql 和 CreateCriteria 之间选择的问题
我对 NHibernate 有一个非常愚蠢的怀疑。存在两个或三个实体,其中两个相关,一个与其他两个实体不相关。我必须通过连接这三个表来获取一些选定的列。使用session.CreateSql()是个好主意还是我们必须使用session.CreateCriteria()。我在这里真的很困惑,因为我无法在这里编写条件查询并被迫使用 CreateSql。请指教。
I have a very silly doubt in NHibernate. There are two or three entities of which two are related and one is not related to other two entities. I have to fetch some selected columns from these three tables by joining them. Is it a good idea to use session.CreateSql() or we have to use session.CreateCriteria(). I am really confused here as I could not write the Criteria queries here and forced to use CreateSql. Please advise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,您应该尽可能避免编写 SQL;
使用 ORM 的优点之一是它与实现无关。
这意味着您不知道(也不关心)底层数据库是什么,并且您实际上可以非常轻松地切换数据库提供程序或调整数据库结构。
如果您编写自己的 SQL 语句,您将面临它们无法在其他提供程序上工作的风险,并且您还必须自己维护它们(例如,如果您将 Id 属性的基础列的名称从“Id”更改为“ Employee_Id',您必须更改 SQL 查询,而使用 Criteria 则无需更改)。
话虽如此,没有什么可以阻止您编写从多个表中提取数据的 Criteria / HQL。例如(使用 HQL):
in general you should avoid writing SQL whenever possible;
one of the advantages of using an ORM is that it's implementation-agnostic.
that means that you don't know (and don't care) what the underlying database is, and you can actually switch DB providers or tweak with the DB structure very easily.
If you write your own SQL statements you run the risk of them not working on other providers, and also you have to maintain them yourself (for example- if you change the name of the underlying column for the Id property from 'Id' to 'Employee_Id', you'd have to change your SQL query, whereas with Criteria no change would be necessary).
Having said that- there's nothing stopping you from writing a Criteria / HQL that pulls data from more than one table. for example (with HQL):
有多种方法可以使用 NH 进行查询。
我建议使用 HQL 或 LINQ 进行常规查询,使用 QueryOver(或 Criteria)进行动态查询,仅在没有其他方法的情况下使用 SQL。
要回答您的具体问题,我不知道:如果查询所需的所有信息都可以在面向对象模型中获得,那么您应该能够通过使用HQL来解决它。
There are multiple ways to make queries with NH.
I would recommend HQL or LINQ for regular queries, QueryOver (resp. Criteria) for dynamic queries and SQL only if there isn't any other way.
To answer your specific problem, which I don't know: If all information you need for the query is available in the object oriented model, you should be able to solve it by the use of HQL.