NHibernate常见错误汇总

  1. NHibernateSample.Data.Test.QueryHQLFixture.WhereTest:

NHibernate.Hql.Ast.ANTLR.QuerySyntaxException : 引发类型为“Antlr.Runtime.NoViableAltException”的异常。 near line 1, column 7 [select from   NHibernateSample.Domain.Entities.Customer c where c.Firstname=‘scenery‘]

错误语法: select  from customer

正确语法: from customer

  1. NHibernateSample.Data.Test.QueryOrderFixture.UseSQL_GetCustomersWithOrdersTest:

NHibernate.Exceptions.GenericADOException : could not execute query

[ select distinct customer.* from Customer customer inner join [Order] o on o.CustomerId=customer.CustomerId where o.OrderDate> @p0 ]

Name:orderDate - Value:2011-9-5 0:00:00

[SQL: select distinct customer.* from Customer customer inner join [Order] o on o.CustomerId=customer.CustomerId where o.OrderDate> @p0]

----> System.IndexOutOfRangeException : CustomerId0_0_

错误写法:return _session.CreateSQLQuery("select distinct {customer}.* from Customer {customer}" +

" inner join [Order] o on o.CustomerId={customer}.CustomerId where o.OrderDate> :orderDate")

.AddEntity("customer", typeof(Customer))

.SetDateTime("orderDate", orderDate)

.List<Customer>();

正解写法:return _session.CreateSQLQuery("select distinct {customer.*} from Customer {customer}" +

" inner join [Order] o on o.CustomerId={customer}.CustomerId where o.OrderDate> :orderDate")

.AddEntity("customer", typeof(Customer))

.SetDateTime("orderDate", orderDate)

.List<Customer>();

  1. NHibernateSample.Data.Test.ManyToManyFixture.UseCriteriaAPI_GetCustomerswithOrdersHavingProductTest: NHibernate.Exceptions.GenericADOException : could not execute query

[ SELECT this_.CustomerId as CustomerId0_2_, this_.Version as Version0_2_, this_.Firstname as Firstname0_2_, this_.Lastname as Lastname0_2_, order1_.OrderId as OrderId1_0_, order1_.OrderDate as OrderDate1_0_, order1_.CustomerId as CustomerId1_0_, products5_.[Order] as Order1_, product2_.ProductId as Product, product2_.ProductId as ProductId3_1_, product2_.Name as Name3_1_, product2_.Cost as Cost3_1_ FROM Customer this_ inner join [Order] order1_ on this_.CustomerId=order1_.CustomerId inner join OrderProduct products5_ on order1_.OrderId=products5_.[Order] inner join Product product2_ on products5_.Product=product2_.ProductId WHERE this_.Firstname = @p0 and order1_.OrderDate > @p1 and product2_.Name = @p2 ]

Positional parameters:  #0>scenery #1>2008-10-1 0:00:00 #2>shirt

[SQL: SELECT this_.CustomerId as CustomerId0_2_, this_.Version as Version0_2_, this_.Firstname as Firstname0_2_, this_.Lastname as Lastname0_2_, order1_.OrderId as OrderId1_0_, order1_.OrderDate as OrderDate1_0_, order1_.CustomerId as CustomerId1_0_, products5_.[Order] as Order1_, product2_.ProductId as Product, product2_.ProductId as ProductId3_1_, product2_.Name as Name3_1_, product2_.Cost as Cost3_1_ FROM Customer this_ inner join [Order] order1_ on this_.CustomerId=order1_.CustomerId inner join OrderProduct products5_ on order1_.OrderId=products5_.[Order] inner join Product product2_ on products5_.Product=product2_.ProductId WHERE this_.Firstname = @p0 and order1_.OrderDate > @p1 and product2_.Name = @p2]

----> System.Data.SqlClient.SqlException : 列名 ‘Order‘ 无效。

列名 ‘Product‘ 无效。

列名 ‘Order‘ 无效。

Map中 column设计错误

  1. NHibernateSample.Data.Test.ManyToManyFixture.UseHQL_GetCustomersWithOrdersHavingProductTest:

NHibernate.Hql.Ast.ANTLR.QuerySyntaxException : c.Orders.elements is not mapped [select distinct c from Customer c , c.Orders.elements o where o.OrderDate > :orderDate]

错误语法:

select distinct c from Customer c ,c.Orders o where o.OrderDate > :orderDate

正确语法:

select distinct c from Customer c inner join c.Orders o where o.OrderDate > :orderDate

  1. NHibernateSample.Data.Test.ManageCustomerTransactionsFixture.DeleteCustomerTest:NHibernate.Exceptions.GenericADOException : could not delete: [NHibernateSample.Domain.Entities.Customer#5][SQL: exec CustomerDelete ? ?]  ----> System.Data.SqlClient.SqlException : ‘@p1‘ 附近有语法错误。
  1. NHibernateSample.Data.Test.ManageCustomerTransactionsFixture (TestFixtureSetUp):NHibernate.MappingException : NHibernateSample.Domain.Mappings.Customer.hbm.xml(29,6): XML validation error: 元素 命名空间“urn:nhibernate-mapping-2.2”中的“class”。 的子元素 命名空间“urn:nhibernate-mapping-2.2”中的“sql-insert”。 无效。应为可能元素的列表: 命名空间“urn:nhibernate-mapping-2.2”中的“filter, resultset, query, sql-query”。。

----> System.Xml.Schema.XmlSchemaValidationException : 元素 命名空间“urn:nhibernate-mapping-2.2”中的“class”。 的子元素 命名空间“urn:nhibernate-mapping-2.2”中的“sql-insert”。 无效。应为可能元素的列表: 命名空间“urn:nhibernate-mapping-2.2”中的“filter, resultset, query, sql-query”。。

原因:增删改顺序错误

正确顺序:增修改查

  1. NHibernateSample.Data.Test.ManageCustomerTransactionsFixture.CreateCustomerTest:NHibernate.Exceptions.GenericADOException : could not execute batch command.[SQL: SQL not available]

----> System.Data.SqlClient.SqlException : 不能将值 NULL 插入列 ‘CustomerId‘,表 ‘NHibernateSample.dbo.Customer‘;列不允许有空值。INSERT 失败。

语句已终止。

原因:用自动生成存储过程的代码顺序错误需要调整代码,查看没有用存储过程的生成的SQL语句

NHibernateSample.Data.Test.ManageCustomerTransactionsFixture.UpdateCustomerTest:

NHibernate.Exceptions.GenericADOException : could not update: [NHibernateSample.Domain.Entities.Customer#6][SQL: exec CustomerUpdate ?,?,?,?,?]

----> System.Data.SqlClient.SqlException : 为过程或函数 CustomerUpdate 指定了过多的参数。

原因:传的参数过多。

NHibernateSample.Data.Test.ManageCustomerTransactionsFixture.UpdateCustomerTest:

NHibernate.Exceptions.GenericADOException : could not update: [NHibernateSample.Domain.Entities.Customer#6][SQL: exec CustomerUpdate ?,?,?,?]

----> System.Data.SqlClient.SqlException : 从数据类型 nvarchar 转换为 int 时出错。

原因:用自动生成存储过程的代码顺序错误需要调整代码,查看没有用存储过程的生成的SQL语句

 

  1. NHibernateSample.Data.Test.ManageCustomerTransactionsFixture.ScalarStoredProcedureTest:NHibernate.MappingException : Named query not known: ScalarSProcs

原因:<spl-query>放在class里,NHibernate找不到,放在class下面即可。

  1. NHibernateSample.Data.Test.StoredProcedureTest (TestFixtureSetUp):

NHibernate.MappingException : unknown class DomainModel.Entities.Customer, DomainModel

----> System.IO.FileNotFoundException : 未能加载文件或程序集“DomainModel”或它的某一个依赖项。系统找不到指定的文件。

  1. NHibernateSample.Data.Test.SchemaUpdateFixture.UpdateExistingDatabaseSchemaTest:NHibernate.MappingException : Could not compile the mapping document: (string)

----> NHibernate.DuplicateMappingException : Duplicate class/entity mapping NHibernateSample.Domain.Entities.Product

原因:Product.hbm.xml映射文件已经存在,需要将其删除后,才能调用。

  1. NHibernateSample.Data.Test.SchemaUpdateFixture.CreateProductSchemaTest:NHibernate.MappingException : No persister for: NHibernateSample.Domain.Entities.CategorySchema

三种原因:

第一hibernate.cfg.xml配置文件错误:<mapping assembly="NHibernateSample.Domain"/>

第二ProductSchema.hbm.xml映射文件生成操作应为:嵌入的资源

第三ProductSchema.hbm.xml映射文件命名错了。少了.hbm.



1、a different object with the same identifier value was already associated with the session。

  错误原因:在hibernate中同一个session里面有了两个相同标识但是是不同实体。

  解决方法一:session.clean()

  PS:如果在clean操作后面又进行了saveOrUpdate(object)等改变数据状态的操作,有可能会报出"Found two representations of same collection"异常。

  解决方法二:session.refresh(object)

  PS:当object不是数据库中已有数据的对象的时候,不能使用session.refresh(object)因为该方法是从hibernate的session中去重新取object,如果session中没有这个对象,则会报错所以当你使用saveOrUpdate(object)之前还需要判断一下。

  解决方法三:session.merge(object)

  PS:Hibernate里面自带的方法,推荐使用。

2、Found two representations of same collection

  错误原因:见1。

  解决方法:session.merge(object)

以上两中异常经常出现在一对多映射和多对多映射中

3、问题情况:使用hibernate来进行对对象的保存操作时,出现了exception,导致数据保存不成功,具体报错如是:

Exception in thread "main" org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:

Exception in thread "main" org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:,这个是因为,在保存的时候,session会检查在内存的外简单的对象跟你new的对象是否一样(不是根据对象的值,而是根据在内存的地址是否一致来比较的),所以new出来的对象是无法跟内存里面的对象一致的,因而,会说不同的对象有一样的id,所以保存数据库的时候就直接根据外键来获取对应的数据库记录来保存对象,所以这个时候用merge方法还是解决不了问题的。

该方法将修改表中记录,其所需要的实体状态为脱管状态,但是注意,它并不影响调用方法前后的状态,也即该实体依然是脱管状,见例6.4。

public void run() {

//创建UserInfo实例

UserInfo userInfo = new UserInfo();

//使之成为脱管状态

userInfo.setId(11112);

//创建UserInfo实例

UserInfo userInfo2 = new UserInfo();

//使之成为脱管状态

userInfo2.setId(11112);

//启动Session

Session session = HibernateSessionFactory.currentSession();

//启动事务

Transaction tx = session.beginTransaction();

//调用merge方法,此时UserInfo实体状态并没有被持久化

session.merge(userInfo);

//调用merge方法,此时UserInfo实体状态并没有被持久化

//但是数据库中的记录被更新了

①session.merge(userInfo2);

//merge方法与update方法的差别在于针对同样的操作update方法会报错

//原因在于update方法使得实体状态成为了持久化状态,而Session中不允许两个持久化实体有同样的持久化标识

②//session.update(userInfo);

//session.update(userInfo2);

//以下两句不会发送SQL,因为userInfo2不是持久化状态的实体

//提交事务

tx.commit();

//关闭Hibernate Session

HibernateSessionFactory.closeSession();

}

userinfo0_.id as id0_0_,

userinfo0_.NAME as NAME0_0_,

userinfo0_.SEX as SEX0_0_,

userinfo0_.roomid as roomid0_0_

from

userinfo userinfo0_

where

userinfo0_.id=?

userinfo

set

NAME=?,

SEX=?,

roomid=?

where

id=?

session.merge()方法会首先发送一句select语句,去数据库端获取UserInfo持久化标识所对应的表记录;然后自动生成一个持久化状态的UserInfo实体,与脱管状态的UserInfo实体做比较是否有所改变;一旦发生了改变,才会发送update语句执行更新。而按执行顺序,若两句session.merge()方法针对同一个脱管状态的UserInfo实体,那其结果只会执行最后一个session.merge()方法所发出的update语句。即使执行了session.merge()方法,UserInfo实体依然是脱管状态,因此③userInfo2. setName("RW5")的语句不会同步数据库中的表。

时间: 2024-08-10 23:17:50

NHibernate常见错误汇总的相关文章

NHibernate常见错误

Oracle 下必须用 Sequence [PrimaryKey(PrimaryKeyType.Sequence,"ID")] 1.提示 ORA-02289: 序列不存在 -- Create sequence create sequence XXXminvalue 1maxvalue 999999999999999999999999999start with 1increment by 1cache 20; 在数据库建个同名字段 测试不通过..求告知..还是提示序列不存在 NHiber

李洪强iOS开发之OC常见错误汇总

// //  main.m //  16 - 常见错误汇总 // //  Created by vic fan on 16/7/13. //  Copyright © 2016年 李洪强. All rights reserved. // OC的常见错误汇总: 1 @interface ... @end  和 @implementation ..@end 之间不能嵌套 2只有类的声明没有类的实现 3 漏写@end 4 两个类的声明顺序可以打乱,但是类的声明一定要在类的实现前面 5 成员变量没有放在

eclipse远程debug服务器上的项目(Tomcat),打开、关闭及常见错误汇总

我们工作中,有时候测试/生产环境,出现的结果会与我们预计的不一样,只看代码又看不出去问题所在,这个时候就需要远程debug下服务器上的项目. 注意:(1)需要debug的代码,本机代码需与服务器上一致.(2)保证服务器下开了允许远程debug的端口 一.打开远程debug 1.右击要debug的项目,Run As ->Debug Configurations,找到Remove Java Application,如下: 填下远程主机IP和端口 备注:如何找预留的debug端口:一般而言,找到对应项

MyEclipse常见错误汇总,中英注释版(长期更新)

No.1 当一条语句漏写分号时错误描述如下 Syntax error, insert ";" to complete Statement(语法错误:插入分号完成语句描述) No.2 当漏写双引号的时候错误描述如下      你好cannot be resolved(你好 不能被解析)

ASP.NET开发网站程序常见错误汇总

数据库连接超时篇若要知道数据库连接超时问题,先看下面一段代码:[Sample-01]: Public Shared Function getOEMPN(ByVal psPN As String, ByRef OEMPN As String) As BSResult 0001 Dim clsResult As New BSResult 0002 Try 0003 clsResult.ResultID = -1 0004 Dim dtResult As New DataTable 0005 Dim

分布式进阶(十一) 常见错误汇总

NO.1 以上添加网桥的命令在Ubuntu14.04中是不可行的.正确的命令如下: brctl addbr br0 ifconfig br0 192.168.1.188 netmask 255.255.255.0 NO.2 造成以上错误的原因是Docker daemon守护进程默认不启动,这也蛮奇葩的,按照提示启动deamon: $ sudo HTTP_PROXY=http://proxy.host:port/ docker -d 执行以后这个窗口变成了一个记录deamon日志的窗口,不可以输入

hadoop 常见错误汇总

1:Shuffle Error: Exceeded MAX_FAILED_UNIQUE_FETCHES; bailing-out Answer: 程序里面需要打开多个文件,进行分析,系统一般默认数量是1024,(用ulimit -a可以看到)对于正常使用是够了,但是对于程序来讲,就太少了. 修改办法: 修改2个文件.        /etc/security/limits.conf vi /etc/security/limits.conf 加上: * soft nofile 102400 * h

Gitolite 常见错误汇总

#1.错误1:在执行 git clone [email protected]:gitolite-admin 提示仓库不存在,或者没有权限. 于是以为别人的文档写的不对,因为真是的 git 仓库是在你当时执行,gitolite setup -pk $HOME/scott.pub 命名时候的用户 home目录下面的 repositories 文件夹下,当然可以指定,于是就想当然的执行以下命令: git clone [email protected]:/home/YourName/gitolite-a

vscode常见错误汇总(长期更新)

1.错误提示 Q:不是每一个红波浪线都是错误,都需要修改 A: 看下面这个地方: 这里的from确实标记了红色波浪线,鼠标放上去还有提示: 但是,这里并不需要修改,因为pep8检查很严格,我们这里前面是针对整个工程,把工程目录添加到了环境变量在前,所以这里不需要修改. 这里可以简单记作:只有运行python脚本的时候运行失败了,才是必须要修改的错误. 其他提示:比如空多少行,空多少格,单行字符串字数过多等,都可以课上的说明为主,忽略多余的警告提示. 2.插件安装 默认Py开头的,在需要时候会有提