NHibernate常见错误汇总

时间:2022-09-17 10:20:05
  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")的语句不会同步数据库中的表。